-
Problems with code
Here the snippet:
Code:
#include <iostream.h>
#include <stdlib.h>
#include <conio.h>
char ch; //Holds current input for evaluation.
int a; //Holds number of chain starts.
int b ; //Holds number of chain ends.
int sum ; //Sum of chains.
void main()
{
a = 0;
b = 0;
sum = 0;
While(ch != '.')
{
ch = getch();
if (ch == 'a')
a++;
if (ch == 'b')
b++;
if (ch == 'a' && b > 0)
{
sum = sum + (a*b);
b = 0;
}
if (ch == '.' && ch == 'c')
{
sum = sum + (a*b);
a = 0;
b = 0;
}
cout << "\n << sum;
}
system("PAUSE");
}
As you can see, the program looks through a string as it is being typed and output the number sub-series in the string that start with 'a' end with 'b' and have no 'c' in the middle. So the string "dsacbsabxbxxa" would return 2 (for "ab" and "abxb").
This code won't compile in Dev-C++ with multiplile errors.
What's the problem?
-
Saw a typo - while shouldn't be capitalized....
What errors are you getting?
-
your while loop should not be capitalized.
and you're missing a " after the \n in your last cout statement to start with.
--system() calls are not always the best way to either.
-
Fixed the while capitalization thingy, thanks.
I get only one error now (instead of seven): "implicit decleration of function "int getchar()".
Whatever that means. I added cout only in this post, actually :), isn't in yet.
-
-
Thanks! It compiles now. It still doesn't work though. And I had some glaringly obvious bugs in the first version. But I've only been coding for a couple of months and that only in school...
Please stick around, if I won't be able to figure this out I may need your help. BTW, latest version of code is:
EDIT: That code was still awfuly buggy. Here's the final algorithm. Still could use some tweaking, I know, but it works. I'm so full of myself it's sad.
Code:
/*Final version with a (finally) working algorithm*/
#include <iostream.h>
#include <conio_mingw.h>
char ch; //Holds current input for evaluation.
int a; //Holds number of chain starts.
int b ; //Holds number of chain ends.
int sum ; //Sum of chains.
void main()
{
a = 0;
b = 0;
sum = 0;
while(ch != '.')
{
ch = getch();
if (ch == 'a' && b > 0 && a > 0)
{
sum += (a*b);
b = 0;
}
else if (ch == 'a')
a++;
else if (ch == 'b' && a > 0)
b++;
else if (ch == '.' || ch == 'c')
{
sum += (a*b);
a = 0;
b = 0;
}
putch(ch);
cout << sum; //Used for debugging.
}
cout << "\n" << sum;
getch();
}
-
> I'm so full of myself it's sad.
:D
One last thing - in the future - remember that main returns an int...