I am trying to have a user enter three inputs: user name, id, and an alternate id. If the user enters a return for user name, the program should end. If the user enters a user name and enters a return for the next two ids, the input should display as invalid. I have tried using cin, fgets, and get(I know get is usually bad programming). When I used cin, I tried using cin.clear() and cin.ignore() to skip a newline entry. The first input always works, but the second input call keeps getting skipped.
Code snippet:
int main(){
string name, altID, tempUWFID;
char input;
cout << "Name> ";
// if (cin.get() == '\n') - This was one way that I tried.
if ((input = getchar()) == '\n')
break;
else
cin >> name;
cout << "UWF ID> ";
if ((input = getchar()) != '\n')
cin >> tempUWFID;
cout << "Alternate ID> ";
if ((input = getchar()) != '\n')
cin >>altID;
cout << "\nThank you for abusing my program, have a nice day!\n";
Output:
Welcome to Voter's Registration
Name> johnny
UWF ID> Alternate ID>
ad
Invalid UWF ID
Name>
Thank you for abusing my program, have a nice day!
Expected Output:
Welcome to Voter's Registration
Name> johnny
UWF ID> somenumber
Alternate ID> someothernumber
Invalid UWF ID
Name>
Thank you for abusing my program, have a nice day!
Here's a quick little program I built, does this solve your problem?
cin itself can read newline characters, and cin >>
... treats newline characters as whitespace and ignores them. cin.getline(...)
and std::getline(cin, ...)
will read and discard newline characters from cin
and then stop reading.
So see if this works for you.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string name = "";
string uwfId = "";
string altId = "";
cout << "\nName> ";
getline(cin, name);
if(name == "" )
return 0;
cout << "\nUWF ID> ";
getline(cin, name);
cout << "\nAlternate ID> ";
getline(cin, name);
if(uwfId == "" || altId == "")
{
cout << "\nInvalid!";
return 1;
}
return 0;
}