Can I use enter as an input? - c++

I am trying to allow the user to either enter a string or just hit enter, and in that case I would use a default string.
cout << "Where should I save the exam (default (./)exam.txt): " ;
cin >> exam_filename;
But right now you can enter a string and it works fine, but if you hit enter it just keeps waiting for the user to type something. Any suggestions??
Okay so when I do this:
string exam_filename;
getline(cin, exam_filename);
if (exam_filename.empty())
// set to default string
now it always sets the string to the default string. It never gives me a chance to enter anything it just moves on the next part of the program autmoatically.

You really want to read a line. Just do it:
string exam_filename;
getline(cin, exam_filename);
if (exam_filename.empty())
// set to default string

Related

How to accept empty input in C++

Accepting user empty input and passing default value from the constructor
I just start learning C++. Now I was trying creating a simple requestion header.
What I was expected is the "ABC Industries" should be used as a default value for the purchaser name and "XYZ Supplier" should be used as a default for the vendor name.
I created a default constructor and a param constructor. Here is my code:
class Requisition{
private:
string purchaser, vendor;
public:
Requisition()
:purchaser("ABC Industries"),vendor("XYZ Supplier"){}
Requisition(string pname, string vname)
:purchaser(pname),vendor(vname){}
void getStaffInput(){
cout << "Enter a purchaser name: ";
cin>>purchaser;
cout << "Enter a vendor name: ";
cin>>vendor;
}
void printHeader(){
cout << "\n********************************************************\nPurchaser: "
<< purchaser <<"\nVendor: "<<vendor
<<"\n********************************************************"<<endl;
}
};
Here is my question:
How can I accept user inputting a empty string (user direct press enter or spacing) because in C++ will force to input something to continue.
If user doesn't key in any data, or just inputting either one of the data (purchaser or vendor), How can I pass the default value to the print function?
int main(){
Requisition req;
req.getStaffInput();
req.printHeader();
}
My program output is forcing the user to input something (can't be blank and spacing), the program should accepting those blank or spacing input and get the default value from the default constructor and display it.
Thanks.
cin into a string will read, effectively, one token. The exact rules are complicated, but it basically pulls content until a space or newline. If you don't input any content, it waits until there's something.
You're looking for getline, which reads until the next newline and returns whatever it finds, even if what it finds is nothing at all.
std::getline(std::cin, purchaser);

How to detect a single Enter key in C++?

I am trying to get an input such as 'Country name'.
If you just press Enter, Country name should be set to default country name (ex)USA). Otherwise, input string would be set to country name. I am confused to how to detect input as a single Enter key or normal string.
Use std::getline() to read a whole line of user input up to the ENTER key (which will be read and discarded for you). If the returned string is empty, replace it with a default value as needed.
std::cout << "Country name: ";
std::countryName;
std::getline(std::cin, countryName);
if (countryName.empty())
countryName = "USA";
Try this
std::cout << "Country name: ";
std::getline(std::cin, countryName);
if(countryName==""){
countryName="USA"
}
also use
cin.ignore(); after every use of cin>> if you have to use getline() in the next line.
you can also use
cin.sync();
cin.get();

Detect a newline character with getline or istringstream

In my program, I'm asking the user for input via getline, and then in a separate class, splitting the string into three different strings which I will then check via a list of pre-determined values.
The way it works now, if someone enters an invalid command, I display "INVALID"
The problem I'm having is with a string containing only spaces or only a single newline character.
Here is what I'm trying to do:
std::string command; // command user enters
getline(std::cin, command); // user input here
std::string tempCheck; // if we have a value in here other than empty, invalid
// use istringstream to grab the words, max of 3
std::istringstream parse{fullCommand}; // parse command into words
if(fullCommand.empty()){ // nothing has been input
std::cout << "INVALID" << std::endl;
return;
}
parse >> command; // stores first word (the command)
parse >> actionOne; // stores second word as parameter
parse >> actionTwo; // stores third word as parameter
parse >> tempCheck;
if(!tempCheck.empty()) {
std::cout << "INVALID" << std::endl;
return;
}
The variable tempCheck basically means that if it goes over three words (the limit I want for commands), then it is INVALID. I also thought that having an empty string would work, but it just ends up in an infinite loop when nothing is input, but I just hit enter.
Here is what I expect my input to be doing (bold is output):
CREATE username password
**CREATED**
LOGIN username password
**SUCCEEDED**
ASDF lol lol
**INVALID**
**INVALID**
REMOVE username
**REMOVED**
**INVALID**
QUIT
**GOODBYE**
Here is what is happening:
CREATE username password
**CREATED**
// newline entered here
And it goes into a seemingly infinite loop. I can still type things, however, they don't actually affect anything. For example typing QUIT does nothing. But, if I restart my program and just type "QUIT" without trying to only use a newline character or only use a space, I get the expected output:
QUIT
**GOODBYE**
So, how do I tell either getline, or my istringstream, that if a user just enters a bunch of spaces and then hits enter, OR if the user just hits enter, display invalid and return? And is there anyway to do this with just getline or istringstream?
Alex, the following code may be helpful:
std::string strip(std::string const& s, std::string const& white=" \t\n")
{
std::string::size_type const first = s.find_first_not_of(white);
return (first == std::string::npos)
? std::string()
: s.substr(first, s.find_last_not_of(white)-first+1);
}
You may apply it before creating the istringstream:
std::istringstream parse{strip(fullCommand)};
The above code was borrowed and slightly modified from the old well-known technique.

Variable doesn't change to last input for that variable

I am trying to make this program currently output the character that they enter, after they enter an error. Currently if you enter a wrong character, I usually just do z, it will give you the desired out of "Error! Please enter a correct type!" and then go back to the start and have you enter the value again. If you enter lower case p it will then prompt for amount of checks written, i usually just say 1. After the checks written input it will then finish by outputting the Account Type that you entered. The problem I am getting is it outputs the z that I entered first and not the p.
How do I go about making the output of the Account Type the last input for that variable. (Global variables aren't allowed)
Code is this:
http://pastebin.com/1DrNcmrR
Jumping right back to the top of the function is bad practice, I woulnd't recommend trying to solve errors by calling the function again, instead how about you enter a while until the input is good?
while(true) {
cin >> answer;
if(toupper(answer) == 'P' || toupper(answer) == 'C') //#include <cctype>
break;
cout << "Error! Please enter a correct type!" << endl;
}
//switch, no default needed

Code Snippet Works in Certain Cases but not as Expected, Why?

I have this code snippet that is supposed to test whether the user enters an integer or not. This works if the user enters letters, but not decimals and I'm left wondering why that is. Here's my code snippet:
Student student;
int id;
while(!(cin >> id))
{
cout << "\nERROR: Please enter a Positive Whole Number" << endl;
cin.clear();
cin.ignore ();
cout << "Enter Student ID: ";
}
Entering A will make it iterate through the while loop, but if I enter 12.5 it drops out of the while loop and keeps going. Isn't it testing whether it will parse to integer or not? Why is it accepting 12.5 but not characters?
cin>>id will succeed as long as it finds something it can convert to an int ("12", in this case). When it reaches something it can't convert, it stops, but if it's read an int already, that counts as success.
To check that everything it read was digits, you might want to do something like using std::getline to read a line of input into a string, then use std::isdigit to test whether those are all digits. Testing a conversion to int (by itself) will only tell you that it found something that could be read as an integer, but won't tell you if that was followed by other things that couldn't be converted to an int.