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();
Related
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);
I have been trying to compare the user input to a file, I was able to open it. let me just show it
cout<< "Please Enter your Student ID: ";
cin >> stdID;
cout<< "Please Enter your Course ID: ";
cin >> courseID;
if the courseID is similar to the prerequisite file, eligible, if not, not eligible..
this is the file
course Prereq
cs111 NA
cs112 cs111
cs240 cs112
cs241 cs240
cs214 cs112
cs215 cs112
cs218 cs111
cs310 cs215
cs311 cs112
cs317 cs215
cs318 cs218
cs324 cs240
cs341 cs241
For something simple like this, I would read the input in a simple while loop, using the input operator >> to read into two strings (and relying on the fact that the operator>> function returns the stream, and that streams can be used in boolean conditions).
Then in the loop compare the user-input with the first string, and if it's a match then output the second string (if it's not e.g. "NA").
So I've run into the following problem. My goal is to create a loop that keeps taking user input over and over until the user doesn't enter anything into 'cin >>', leaves the line blank, and simply presses the ENTER key to move on, at which point the program is supposed to break out of the loop and continue on with the rest of program execution. Something like this:
do {
cout << "\nEnter a name: ";
cin >> input1;
if (input1.empty())
{
break;
}
else
{
user_name = input1;
}
} while (!input1.empty());
As you can see, I've already tried using the empty() function, but that didn't work, the program simply stays in the loop and doesn't break out, no matter how many times I press enter. It just keeps prompting me to enter a name. I've also tried using something like
if (input1 == "")
but that doesnt work either. Can anyone help? How do I break out of this loop?
UPDATE: OK guys, I've tried your recommendations, and it worked! Thank you so much! Unfortunately, although the getline function works, it has also created a new problem for me. Basically, in the first initial loop, the program prompts for a name, I type in a name, and the name is stored in user_name. However, in the SECOND loop, the program doesn't even give me the chance to enter any input, it simply prints "Enter a name: ", and then instantly exits out of the loop, and continues on with the rest of program execution. Why is this happening?
Use this getline(std::cin, input1):
while (getline(std::cin, input1))
{
if (input1.empty())
break;
username =input1;
std::cout << input1 << std::endl << "Enter Input : ";
}
Use std::getline(cin, input1); instead to read a line from the console.
Using cin directly reads exactly one word from stdin. If the user does not input anything, no word has been given and cin does not return yet (your empty check is not even executed).
After you use std::getline you can leave your empty-check as-is:
std::getline(cin, input1);
if(input1.empty())
break;
BTW: In C++ you should also check if the underlying stream has run into an error. So check the return code of cin or getline. This can be done with the following code:
if(!std::getline(cin, input1))
// I/O error
In general, looping until an empty line is entered would be:
while ( std::getline( line ) && !line.empty() ) ...
If you need a prompt: the prompt is part of the input logic, and
should be implemented as such:
std::string
getlineWithPrompt( std::string const& prompt )
{
std::cout << prompt;
std::string results;
return std::getline( std::cin, results )
? results
: std::string();
}
You then do something like:
std::string line = getlineWithPrompt( "prompt for first line" );
while ( !line.empty() ) {
// ...
getlineWithPrompt( "prompt for further line" );
}
(This is actually somewhat simplified, as it treats hard errors
on input, end of file, and empty lines identical, which is
rarely the right thing in professional software. But for
learning purposes, it should be sufficient.)
Cin won't read the whitespace that you call an empty line. Getline may do this, but I am not entirely sure. You could define an end character that the user would type and check for that. Gets would also work, it will just set the starting character to 0x0. Be careful with gets(), it is prone to allow buffer overflows.
This works as well:
char line[128];
do
{
cout << "Enter something: ";
gets(line);
} while (strcmp(&line[0], "\0") != 0);
#JamesKanze
So something like this to exit the while loop?
string str = "foo";
while (str == "foo"){
getline(cin, str);
}
str = "foo";
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
The system did this:
Please input the Full Name of the user:Please input the Full Name of the user:
It output the string "Please input the Full Name of the user:" twice , how do i change the code to make it just cout once
string fullname = "";
do
{
cout << "Please input the Full Name of the user: ";
getline (cin,fullname);
}while(fullname.length()<1);
C++ What is causing the system to output twice
You could try flushing your input stream to get rid of leftover newlines:
std::cin.ignore(x);
(with x being the number of characters to ignore, e.g. INT_MAX).
Simple solution would be to move the std::cout statement outside of the do-while loop.
string fullname = "";
cout << "Please input the Full Name of the user: ";
do
{
getline (cin,fullname);
}while(fullname.length()<1);
You are performing an input operation without checking the result, which is a hard programming and understanding error. Do this instead:
for (std::string line; ; )
{
std::cout << "Name: ";
if (!std::getline(std::cin, line) || !line.empty()) { break; }
}
The first condition checks whether the input succeeded (which is false when the input stream is closed), and the second checks whether the read line is non-empty. The short-circuit semantics of || make the second check legal.
As others have pointed out the problem is that you have an extra '\n' character on the input stream.
Contrary to the popular answer I don't think flushing (ignore()) the current input is a good solution. You are treating the symptom not the problem. If you are using ignore() you are potentially throwing away user input that you might actually want or something that could have detected an error from the user:
> Input Your age
> 36xxxx
// If you use
std::cin >> age;
// Then sometime later in your code you use
// ignore to make sure that you have "correctly" skipped to the next new line
std::ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// You have now just ignored the fact that the user typed xxx on the end of the input.
// They were probably doing that to force an error in the code or something else erroneous
// happened but you just missed it with std::ignore()
The best solution is not to get into this situation.
This problem is caused by using a combination of operator<<() and std::getline() to parse user input. I love using operator<<() to parse normal or regular input; but manual user input (ie Question/Answer) is harder to predict and users input is line based (there input ends at the '\n' character because the buffer is flushed when they hit <enter>).
As a result when I parse manual user input I always use std::getline(). This way I know I got the whole of their answer. It also allows me to validate the input to make sure there was not a typing error.
std::cout << "What is your age\n";
std::string line;
std::getline(std::cin, line); // Get user input
// Use stream for easy parsing.
std::stringstream linestream(line);
// Get value we want.
linestream >> age;
// Validate that we have not thrown away user input.
std::string error;
linestream >> error;
if (error.length() != 0) { /* do stuff to force user to re-input value */ }