-
need help BAD!!@!!!
WHY DOESN"T THIS WORK, GRRRR !@!@!@!@
the project ask the user to enter a string and then prompts the user to enter a character. the program should display the location of the first occurrence of the character in the string.
for example: the user enters the string "abcde", and the character "d", the program should say the character d is character number 4 in the string.
Code:
#include <iostream.h>
#include <iomanip.h>
int main()
{
char line[50];
char * ch_ptr;
char oneChar;
int count = 0;
cout << "\nEnter a string of characters:\n\n";
cin.getline(line, 50);
cout << "\nEnter one character in the previous string\n";
cin >> oneChar;
for (ch_ptr = line; *ch_ptr == ' '; ++ch_ptr);
while (*ch_ptr != '\0')
{
++count;
if
((ch_ptr == oneChar) && (*ch_ptr != ' '))
{
cout << "\nThe string you entered is in the " << count << " space .\n\n";
}
else
(*ch_ptr != oneChar)
{
cout << "\nYou have entered the wrong character";
}
}
return 0;
}
can nebody help me out on this, i would greatly appreciate it =0)
-
It doesn't work because in your while-loop ch_ptr always points to the same location.
Add
ch_ptr++;
to your loop.
And change the line:
if ((ch_ptr == oneChar) && (*ch_ptr != ' '))
to
if ((*ch_ptr == oneChar) && (*ch_ptr != ' '))
-
Or just use this code : (I modified your code a bit)
-
Thanks =0)
Hey thanks a lot guys, i do really appreciate the extra hand. I got it to work fine and everything except when i press an incorrect character, it prints like 3 times, strange but yea, i just want to say thanks again for all the help =0)
-
That's a cool thing. You should put a loop in it so that it will keep cycling through.
like "go again? Y enter a string..."
-
It's probably giving you the message about how the character isn't in the string because its looping through each character and giving you a message for that character. You're better off setting a boolean isInString = false, then setting it true if and when it finds the right character; then, after the loop is over, print the "character not found" message if isInString is still false.
Better yet use the string class, which has a find function, instead of the char*.