Ok, I am newish at programming in c++ and am doing a computer science program in school. For my latest project I have come to a bit of a dead end and was hoping for some help with loops and ignoring characters.

The program is quite simple, it is a tax calculator. The program asks the user if they have any dependents. The user must answer with a y/Y/n/N(this part is fine, and is not where I am having issues) or it is acceptable for the user to enter a word. In the case that a user enters a word, I have to take the first character of the word and if it is a(n) y/Y/n/Y then the input is valid, and all other characters are ignored. If the first character is not a(n) Y/y/n/N then it is supposed to fail and then I have to use while loops.

My problem is I don't know how to ignore all characters after the first, and just validate the first character. I would really appreciate help on this. Oh, and I cannot use cin.ignore().

The program then goes on to promt the user for their income, then calculates it, this part I have no problem with.

Thanks for your help.

You isolate a character int a string using the [] operator.

string input = "yes";
char firstLetter = input[0];

if (firstLetter == 'y' || firstLetter == 'Y' || firstLetter == 'n' || firstLetter = 'N')
   cout << "Input is valid\n";
else
   cout << "Input is invalid.\n";

>>My problem is I don't know how to ignore all characters after the first

Use getline() to get the entire string from the keyboard, then follow Vernon's suggestion.

well it looks like your guys stuff will work, unfortunately I can only use what I learned in class.

I have to do this:
The program must keep asking the user for an answer until it is correct.
If the first data item on the line is correct(y/Y/n/N) then it can be used. Regardless, all other data on the line must be ignored.
Note that you are not permitted to use strings - you may only use variables of type char and float. As well, you cannot use the function ignore.

Basically I am only allowed to use cout, cin, loops(mostly while loops for this program) and I guess if/else statements.

Any ideas? I have tried a variety of do while and just while loops, and even tried if loops, but I am getting no where.

Edited 7 Years Ago by jupitertrooper: n/a

For the sake of not doing your homework, I will offer some advice only. The last character you will read on the line is '\n'. So if you read and ignore characters in a loop until '\n' is found, it will have the same effect as this call to ignore:

cin.ignore(numeric_limits<streamsize>::max(), '\n');

Edited 7 Years Ago by Tom Gunn: n/a

I may have solved my problem, I was using || instead of && in the while statements, and switching them seems to have solved my problem, I'll get back to you guys if it isn't the solution.

This article has been dead for over six months. Start a new discussion instead.