I'm trying to read in a string of text using getline. For some reason, it prints 'Please enter your selection' twice:
Please enter your selection
Please enter your selection
If I key invalid text, it loops again, and only prints the one time each loop thereafter.
while (valid == false) {
cout << "Please enter your selection" << endl;
getline (cin,selection);
// I have a function here which checks if the string is valid and sets it to true
// if it is valid. This function works fine, so I have not included it here. The while
// look breaks correctly if the user enters valid input.
}
Does anybody have any idea why this may be occurring?
Thank you
Probably there's something still in the input buffer from a previous operation when you enter the loop.
It's picked up by the getline, found to be invalid, then the loop runs again.
By way of example, let's say that, before you enter the loop, you read a single character. But, in cooked mode, you'll need to enter the character and a newline before it's actioned.
So, you read the character and the newline is left in the input buffer.
Then your loop starts, reads the newline, and deems it invalid so it then loops back to get your actual input line.
That's one possibility though, of course, there may be others - it depends very much on the code before that loop and what it does with cin.
If that is the case, something like:
cin.ignore(INT_MAX, '\n');
before the loop may fix it.
Alternatively, you may want to ensure that you're using line-based input everywhere.
Here's some code to see that scenario in action:
#include <iostream>
#include <climits>
int main(void) {
char c;
std::string s;
std::cout << "Prompt 1: ";
std::cin.get (c);
std::cout << "char [" << c << "]\n";
// std::cin.ignore (INT_MAX, '\n')
std::cout << "Prompt 2: ";
getline (std::cin, s);
std::cout << "str1 [" << s << "]\n";
std::cout << "Prompt 3: ";
getline (std::cin, s);
std::cout << "str2 [" << s << "]\n";
return 0;
}
Along with a transcript:
Prompt 1: Hello
char [H]
Prompt 2: str1 [ello]
Prompt 3: from Pax
str2 [from Pax]
in which you can see that it doesn't actually wait around for new input for prompt 2, it just gets the rest of the line you entered at prompt 1, because the characters e, l, l, o and \n are still in the input buffer.
When you uncomment the ignore line, it acts in the manner you'd expect:
Prompt 1: Hello
char [H]
Prompt 2: from Pax
str1 [from Pax]
Prompt 3: Goodbye
str2 [Goodbye]
I would use debugger (for example gdb in linux) to check why. Why make a theories when you can find out the real answer?
Related
i have a simple code that gets name of user as an array with getline() public function. when it reaches to char '$' i want to stop getting input from user and go to next line.but immediately after reaching char'$'(my delimiter)it ignores line 5 and runs line 6 and i don't know why!!!
#include <iostream> // std::cin, std::cout
int main () {
char name[256], title[256];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256,'$'); //Line 3
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256); // Line 5
std::cout << name << "'s favourite movie is " << title; // Line 6
return 0;
}
Let me guess your input looks like this:
> ./myProg
Please, enter your name: noob$
lease, enter your favourite movie: Top Gun
noob's favourite movie is
>
Here we see that you entered: noob$<return> followed by Top Gun<return>.
The problem is that the input the computer is seeing is:
noob$\nTop Gun\n
OK. So what is happening in the code.
std::cin.getline (name,256,'$'); // This reads upto the '$' and throws it away.
So your input stream now looks like:
\nTop Gun\n
Notice the '\n' at the front of the stream.
Now your next line is:
std::cin.getline (title,256); // This reads the next line.
// But the next line ends at the next new line
// which is the next character on the input stream.
// So title will be empty.
To fix it you need to read off that empty line.
A better way to fix it is to not require the name to be terminated by '$'. User input is usually better done a line at a time. As the user hits return the buffer is flushed and the stream actually starts working. The program is not doing anything (apart from waiting) until that buffer is flushed to the stream (this is usally on return but can happen if you just type a lot).
It seems to work like this:
#include <iostream> // std::cin, std::cout
int main () {
char name[256], title[256], endOfLine[2];
std::cout << "Please, enter your name: ";
std::cin.getline (name,256,'$'); //Line 3
std::cin.getline(endOfLine, 1);
std::cout << "Please, enter your favourite movie: ";
std::cin.getline (title,256); // Line 5
std::cout << name << "'s favourite movie is " << title; // Line 6
return 0;
}
You can use the following solution to solve your problem:
.....getline(title,256,'$')
// ^
// |
// this is where the delimiter goes in your function call
So I recently finished a beginner'c course on C++, and wanted to make my own "chat bot" since apparently it's easy and been done a million times. The problem I'm having, is that when the user input matches more than one possibility in my 'if' statement, it issues the command more than once.
class response{
public:
void answer() {
string x;
cin >> x;
if (x=="Hello"||x=="hello"||x=="Hi"||x=="hi"||x=="hey"||x=="Hey") {
cout << endl << "Hello!" << endl << endl;
}
else {
cout << endl << "I didn't understand that." << endl << endl;
}
} };
For example, if you input: "hey hi", you get: "Hello! Hello!"
Or if you input "hey squid" you get "Hello! I didn't quite understand that."
And so on and so on. I'm wondering if there is any way to make it so that, unless your entire string matches the exact x== values, it will execute the else statement, and only execute it once.
Edit: The solution worked. Thanks for all the help! Some of you were asking about how I was using the class statement in main. I hope this helps clarify how I used it:
int main()
{
cout << "Hello! I am Drew Bot 1.0." << endl << endl;
for(;;){
response test;
test.answer();
}
}
For what you describe to occur (and it would make sense because you're writing a chat bot), response::answer() would have to be called in a loop.
The tokens of std:cin are delimited by the space character, so when you stream it into a variable you are only getting the first word and the rest of the words remain in the std::cin stream. The part that is catching you is that is if std::cin already has a token, it does not wait for user input.
So, if you type "hey hi hello squid" in the first call to response::answer, it will only check the first word. Subsequent calls will check the rest of the words without prompting the user until nothing remains in the input stream.
A solution would be to use getline (std::cin, x); in place of std::cin >> x.
getline will read to the next newline or EOF, but you can also specify your own delimiter: getline(std::cin, x, ' ');
I'm working on a simplish game (this isn't the whole code, just the bit that I'm having issues with) and I've run into this issue; After the condition is furfilled, it goes back to the start and it offers me to reenter the string, however, whatever I enter, I just get 'Not Valid'. Does anyone know why? I'm using the GNU C++ Compiler.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string command;
mainscreen:
cout << "blab";
getlinething:
cin.ignore();
getline(cin, command);
if (command == "task")
{
goto mainscreen;
}
else
{
cout << "Not valid.";
goto getlinething;
}
return 0;
}
When I run your code with a debug print it shows that each time you read a new command you are loosing the first char of the string. In fact, when I remove your cin.ignore() it works fine.
Also, have a look at this while to see if it fits your needs:
cout << "blab";
while(1){
getline(cin, command);
if(command == "task"){
cout << "blab";
getline(cin, command);
}
else{
cout << "Not valid.";
}
}
For debugging purpose at least, why not do
cout << "'" << command << "' Not valid" << endl ;
Alright, I tested it out. Without cin.ignore(), I cannot enter the data into the string at all.
The first time I enter it captures everything. So if I wrote task, the string would say 'task', however the second time I entered it, it would say 'ask'. I don't really know why it's doing that.
The cin.ignore() line will always discard one character by default (unless it encounters EOF, which would be a fairly deliberate act on cin).
So, let's say the user enters task and then hits the enter key. The cin.ignore() will discard the 't', and the command string will contain "ask". If you want to get a match, the first time through, the user will need to enter ttask. The newline will be discarded, in either case. The same will happen until a match is encountered.
I'm currently learning C++ and I was asked to write a code using the while function. The code runs, but it gives does not print the line Dear .... What did I do wrong here?
cout << "Hello! Please write your recipient and the letter, then press enter:\n";
string name{ "" };
string current{ "" };
string letter{ "" };
cin >> name;
while (cin >> current){
if (current != name){
letter += " " + current;
}
}
cout << "Dear " << name << "," << letter;
keep_window_open();
return 0;
To output the result you have to make cin >> current false. To do this, use Ctrl-D to send end of file (EOF) to cin which will cause the loop to stop executing.
Edit: Apparently in Windows, the sequence is Ctrl-Z.
Edit: As #pdw noted, cout will need to be flushed. This is usually done when there is a newline character, but since you don't have one you can use std::flush or std::endl:
cout << "Dear " << name << "." << letter << std::flush;
while (cin >> current)
To make this loop interrupt you need to put end of stream marker into std::cin. Type Ctrl-Z on Windows or Ctrl-D on Unix like systems at the end of input to achieve that.
You have an infinite loop here. while (cin >> current) will always evaluate to true, and will just continuously wait for user input. That is why you never reach the last line of code. You are just continuously creating new values for current on each input in the prompt and then adding them to letter. I would recommend not using a while loop, or set some escape input. For example, if the user enters done, exit from the loop, using break;
This question already has answers here:
Need help with getline() [duplicate]
(7 answers)
Closed 7 years ago.
Hey, I'm trying to write a program that will accept new tasks from people, add it to a stack, be able to display the task, be able to save that stack to a text file, and then read the text file. The issue comes when I am trying to accept input from the user, whenever you enter a string with a space in it, the menu to choose what to do just loops. I need a way to fix this. Any help would be greatly appreciated.
// basic file io operations
#include <iostream>
#include <fstream>
#include <stack>
#include <string>
using namespace std;
int main () {
//Declare the stack
stack<string> list;
//Begin the loop for the menu
string inputLine;
cout << "Welcome to the to-do list!" << endl;
//Trying to read the file
ifstream myfile ("to-do.txt");
if(myfile.is_open()){
//read every line of the to-do list and add it to the stack
while(myfile.good()){
getline(myfile,inputLine);
list.push(inputLine);
}
myfile.close();
cout << "File read successfully!" << endl;
} else {
cout << "There was no file to load... creating a blank stack." << endl;
}
int option;
//while we dont want to quit
while(true){
//display the options for the program
cout << endl << "What would you like to do?" << endl;
cout << "1. View the current tasks on the stack." << endl;
cout << "2. Remove the top task in the stack." << endl;
cout << "3. Add a new task to the stack." << endl;
cout << "4. Save the current task to a file." << endl;
cout << "5. Exit." << endl << endl;
//get the input from the user
cin >> option;
//use the option to do the necessary task
if(option < 6 && option > 0){
if(option == 1){
//create a buffer list to display all
stack<string> buff = list;
cout << endl;
//print out the stack
while(!buff.empty()){
cout << buff.top() << endl;
buff.pop();
}
}else if (option == 2){
list.pop();
}else if (option == 3){
//make a string to hold the input
string task;
cout << endl << "Enter the task that you would like to add:" << endl;
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
cin.ignore();
//add the string
list.push(task);
cout << endl;
}else if (option == 4){
//write the stack to the file
stack<string> buff = list;
ofstream myfile ("to-do.txt");
if (myfile.is_open()){
while(!buff.empty()){
myfile << buff.top();
buff.pop();
if(!buff.empty()){
myfile << endl;
}
}
}
myfile.close();
}else{
cout << "Thank you! And Goodbye!" << endl;
break;
}
} else {
cout << "Enter a proper number!" << endl;
}
}
}
You have to add cin.ignore() right after options is chosen:
//get the input from the user
cin >> option;
cin.ignore();
And cin.ignore() is not necessary after your getline:
getline(cin, task); // THIS IS WHERE THE ISSUE COMES IN
//cin.ignore();
The problem is in options - if you didn't call cin.ignore() after it, options will contain end of line and loop will continue...
I hope this helps.
Don't do this:
while(myfile.good())
{
getline(myfile,inputLine);
list.push(inputLine);
}
The EOF flag is not set until you try and read past the EOF. The last full line read read up-to (bit not past) the EOF. So if you have have zero input left myfile.good() is true and the loop is enetered. You then try and read a line and it will fail but you still do the push.
The standard way of reading all the lines in a file is:
while(getline(myfile,inputLine))
{
list.push(inputLine);
}
This way the loop is only entered if the file contained data.
Your other problem seems to stem from the fact that you have:
std::getline(std::cin,task); // THIS is OK
std::cin.ignore(); // You are ignoring the next character the user inputs.
// This probably means the next command number.
// This means that the next read of a number will fail
// This means that std::cin will go into a bad state
// This means no more input is actually read.
So just drop the cin.ignore() line and everything will work.
Instead of using ">>" directly on your stream you might consider using getline and then attempting to fetch your option from that. Yes, it's less "efficient" but efficiency isn't generally an issue in such situations.
You see, the problem is that the user could enter something silly here. For example, they could enter something like "two", hit enter, and then your program is going to pitch a fit as it happily continues trying to decipher an empty option over and over and over and over again. The user's only recourse the way you have it set up (and the way those recommending use of ignore() are recommending) is to kill your program. A well behaved program doesn't respond in this way to bad input.
Thus your best option is not to write brittle code that can seriously break down with the most modest of user ignorance/malfunction, but to write code that can handle error conditions gracefully. You can't do that by hoping the user enters a number and then a newline. Invariably, someday, you'll bet poorly.
So, you have two options to read your option. First, read a full line from the user, make sure the stream is still good, and then turn the string you get into a stream and try to read your integer out of it, making sure this other stream is still good. Second option, attempt to read a number, verify that the stream is still good, read a line and make sure the stream is still good and that your string is empty (or just ignore it if it isn't, your choice).
#Vladimir is right. Here is the mechanism behind the bug:
When you enter option '3', what you actually put into stream is "3\n". cin >> option consumes "3" and leaves "\n". getline() consumes "\n" and your call to ignore() after getline() waits for user input.
As you can see, teh sequence of events is already not what you expected.
Now, while ignore() is waiting for input, you type in your line. That line you're typing is what will go to "cin >> option.
If you just give it one symbol, ignore() will dispose of it for you, and option will be read correctly. However, if you give it non-numeric symbols, stream will set failbit when trying to read the option. From that point on, your stream will refuse to do anything. Any << or getline will not set any new values in the variables they are supposed to change. You'll keep 3 in option and "" in task, in a tight loop.
Things to do:
always check cin.eof(), cin.fail() and cin.bad().
always initialize your variables and declare them in the narrowest scope possible (declare option=0 right before it's read).
I just figured out a way to kind of hack through it, not the greatest but it works. Create a character array, and then accept input in the array, and then put everything into the array into the string.
char buff[256];
cout << endl << "Enter the task that you would like to add:" << endl;
cin >> task;
task += " ";
cin.getline(buff, 256);
for(int i = 1; buff[i] != 0; i++){
task += buff[i];
}