This question already has answers here:
Basic I/O not working in Visual C++ 2010?
(2 answers)
Closed 8 years ago.
I still don't know how this works with Visual Studio.
Supposedly it keeps my console open, but it doesn't. It still flashes and closes.
Am I doing something wrong?
#include <iostream>
using namespace std;
int main()
{
int a;
cout << "Please enter an integer: ";
cin >> a;
if (a == 1)
{
cout << endl << "You typed 1.";
}
else
cout << "That's not 1.";
cin.get();
return 0;
}
As it was already pointed out in the comments the problem is that the input buffer contains the symbol of the Enter key that is read by cin.get();
You can use either the following sequence
char c;
cin >> c;
Or before cin.get() you should call cin.ignore. For example
cin.ignore( numeric_limits<streamsize>::max(), '\n' );
cin.get();
In the last case you must include header <limits>
Related
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Getline jump on next cin and skip the previous cin
(1 answer)
Closed 10 months ago.
Today i started working on a quite big project and found this problem I've never found. I always used to reset the cin stream with the usage in sequence of sync() and clear(). But after i changed my compiler (a month ago i switched from standalone minGW to minGW through msys2) to have filesystem included in the std library, it seems this combination doesn't work anymore. Now I'm asking 2 different questions:
Does anyone knows why exactly? (I'm using gcc 11.2.0, just checked on my CMD)
How can I solve this problem?
Here's the example code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int number;
string s;
cout << "insert a number" << endl;
cin >> number;
cin.sync();
cin.clear();
cout << "Now insert a string" << endl;
getline(cin, s);
cout << "This is your number: " << number << endl;
cout << "This is your string: " << s << endl;
}
And here's the terminal:
insert a number
8
Now insert a string
This is your number: 8
This is your string:
Obviously as you can see it doesn't wait for my input and i think it gets my enter as a char for the string. That's why it prints what seems to be nothing (it's simply '\n')
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 2 years ago.
Im a new user of c++ and I am stuck with a problem.
If the input for the int variable 'x' is anything other than a number, then c++ seems to skip the cin associated with the char variable 'y'. I tried to use cin.ignore and cin.clear, but they dont seem to work. Any ideas on how to make the program still ask the value for char 'y' when the value for int 'x' is anything but a number(eg. 'a' '*' '') ?
#include <iostream>
using namespace std;
int main()
{
int x;
char y;
cout << "num: ";
cin >> x;//int input
cout << endl;//blank line
cout << "char: ";
cin >> y;//char input
cout << endl;//blank line
return 0;
}
Are you passing parameters to ignore?
The first parameter is the maximum of chars to be ignored and the second one is the flag that it should stop ignoring after findind it (which in the example below I've put '\n')
cin.clear();
cin.ignore(1000, '\n');
To summarize, the code says: Clear up to 1000 chars or up to the first '\n'.
This question already has answers here:
cin input (input is an int) when I input a letter, instead of printing back incorrect once, it prints correct once then inc for the rest of the loop
(2 answers)
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
Closed 4 years ago.
I've been coding in C++ for all of a few days, so please talk to me like I'm a baby. With that out of the way,
I've made a short algorithm that asks a set of questions (to be answered 0 for no and 1 for yes) and stores the user's answer as an integer. Everything works as expected as long as the user only inputs integers (or, in one case, a string with no spaces).
But if the input doesn't match the variable type, the program immediately outputs this infinite loop that appears later in the program. That loop is supposed to print a question, wait for input, and then ask again if the answer isn't '1', but in the failure state it just prints the question without end. I can't see any reason why the previous questions would be connected to this. It doesn't happen on the questions that come after it, if that's a clue.
Here's a pared-down version of my code with, I hope, all the important information intact:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int answer1;
string answer1C;
int answer2;
int answer2B;
int score;
score = 0;
cout << "Question 1" << endl;
cin >> answer1;
if (answer1 == 1)
{
++score;
//some other questions go here
cout << "Question 1C" << endl;
cin >> answer1C;
if (answer1C.size() == 6)
{
++score;
}
}
cout << "Question 2" << endl;
cin >> answer2;
if (answer2 == 0)
{
cout << "Question 2B" << endl;
cin >> answer2B;
if (answer2B == 0)
{
--score;
}
while (answer2B != 1) //Here is the infinite loop.
{
cout << "Question 2B" << endl;
cin >> answer2B;
}
}
cout << "Question 3" << endl;
//and so on
return 0;
}
I would love to have it accept any input and only perform the ensuing steps if it happens to meet the specified conditions: for instance, in question 1.2, it only awards a point if the answer is a string of length 6, and otherwise does nothing; or in question 2.1, it repeats the question for any input that isn't '1', and moves on if it is.
But in any case whatsoever, I need it to do something else when it fails. Please help me figure out why this is happening. Thank you.
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Using getline() in C++
(7 answers)
Closed 4 years ago.
Can anyone explain why I am having trouble with the below C++ code?
#include <iostream>
using namespace std;
class stud
{
public:
string name,adrs;
long long unsigned int mob;
};
int main()
{
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
for(int i = 0; i < num; i++)
{
cout << endl << "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin, s[i].name); // this line skips some data before even they are
//entered and there is no error while compiling
}
system("CLS");
for(int i = 0; i < num; i++)
{
cout << endl << " Student " << i+1 << " name is: ";
cout << s[i].name << endl;
}
return 0;
}
When I try to input a string value for an object in the array as above, using getline() without any delimiter (which uses a new line by default), I don't get correct output since some other data is automatically being skipped.
But, when I use getline() as follows instead of above, it works fine, but it needs a delimiter at the end:
getline(cin, s[i].name, '.');
Please help me find a solution. I think the Enter key is pressed several times at one key press, and that's why the getline() skips some data. I'm not sure about this, though.
before correcting you program one thing to know is that
Actually, a newline is always appended to your input when you select Enter or Return when submitting from a terminal.
cin>> doesn't remove new lines from the buffer when the user presses Enter.
This has little to do with the input you provided yourself but rather with the default behaviour std::getline() exhibits. When you provided your input for the name (std::cin >> num;), you not only submitted the following characters, but also an implicit newline was appended to the stream, getline() mistakes this for user input along with enter.
It is recommended to use cin.ignore() to get rid of those extra characters after using cin>>(whatever) if you are going to use getline(cin,any string) later.
Edit this part of your code:
stud s[10];
unsigned int num;
cout << endl << "Enter the number of students(<10): ";
cin >> num;
cout << endl;
cin.ignore();//just add this line in your program after getting num value through cin
//fflush(stdin);
//cin.sync();
//getchar();
for(int i = 0; i < num; i++)
{
cout<<endl<< "Enter student " << i+1 << " name(put '.' at end and press enter): ";
getline(cin,s[i].name);
}
system("CLS");
you can use and may be tempted to use fflush(stdin) also but it is not recommended as it has undefined behaviour, as
According to the standard, fflush can only be used with output buffers, and obviously stdin isn't one.
about cin.sync():
using “cin.sync()” after the “cin” statement discards all that is left in buffer. Though “cin.sync()” does not work in all implementations (According to C++11 and above standards).
you can also use getchar() to get the newline caused by Enter
This question already has answers here:
C++ Issue with cin and CTRL + Z
(2 answers)
Closed 5 years ago.
I'm going through B. Stroustrup's Programming Principles and Practice Using C++ and I encountered a problem doing one of the exercises. I'm using Windows 10 (I believe, that's relevant here).
The code below is supposed to ask the user for words, which are to be printed back. However, if a word is "broccoli", then instead of "broccoli", "BLEEP" will be printed.
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string bad_word = "broccoli";
cout << "type in some words\n";
vector <string> words;
for (string temp; cin >> temp; )
words.push_back(temp);
cout << "There are " << words.size() << " words in vector 'words'.\n";
for (string word : words) {
if (word != bad_word)
cout << word;
else
cout << "BLEEP";
}
keep_window_open();
return 0;
}
So, I have my program ask me for words, I print some, then hit Ctrl+Z + Enter, and nothing happens. If I do that again, the console closes. Why doesn't it print the number of words as specified by this line?
cout << "There are " << words.size() << " words in vector 'words'.\n";
Why does the program finish execution after I hit Ctrl+Z+Enter the second time?
I want to understand what the problem really is here.
Thank you.
ctrl-z is an end of file signal.
This disables reading from the input stream (cin).
So your keep window open function returns immediately without waiting(because reading is not possible), and your console closes.