I recently faced a problem with the cin statement in C++.
string s;
cin >> s;
cout << 1;
In this code 1 is printed on the screen if input to s is '010' and programs time limit exceeds on ideone for the same code but input being '1010'. I don't think it is due to the '\n' left in the buffer after using cin as this is the only instance I have taken input in the program. You can find my code at http://ideone.com/7VEsbu.
Problem is elsewhere. Try adding <<endl to the line with cout - you will get an error, but see the output. Ideone isn't flushing stream instantly after cout, and that's why you don't see your output. endl forces stream flush.
A wild guess would be that last while loop never terminates.
Related
I've tried googling for this, but was unable to find an answer.
Sometimes, when I'm using std::cin, whatever I input is being printed again to the console after hitting Enter. It might be limited to my machine/compiler but I'm completely clueless as to why this happens, and why it happens only occasionally.
This is some example code:
int n;
std::cout << "Enter n:" << std::endl;
std::cin >> n;
Which outputs (if I input, say, 3)
Enter n:
3
3
But only the 3 that is on the line after the Enter n: is the one I input. Why does this happen and how can I prevent it?
Edit: As this could be an IDE issue, I'm using CLion 2018.1.3
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
int n;
while(cin>>n)
cout << n; // Run by the program if received an int value
cout << "Break from loop"; // Run by the program
cin >> n; // Skipped by the program
cout << n; // Run by the program
cant accept another input after terminating the while loop using characters.
How to accept another input if the input within the loop has been terminated using non-integer/floating-point values.
If you are not terminating the program by returning end of file (i.e. Ctrl-D) or terminating the program altogether (i.e. Ctrl-C).
That is, if you exit the loop via incorrect data type, such as typing in the letter d instead of an integer, you can follow the while loop with cin.clear() and getline(cin, str), where str is some string you declare ahead of time.
You should be able to accept input for the second cin at after this.
So,
string str;
int n;
while(cin>>n)
cout << n << endl;
cin.clear();
getline(cin, str);
cout << "Break from loop" << endl;;
cin >> n;
cout << n;
int n;
while(cin>>n) // Keep asking for value to input
cout<<n<<"\n"; // This loop will never terminate for any Supplied val
//Above loop will terminate only when no more valued is supplied to code
// Hence once, we stopped entering the value, code will execute next line
// And end without asking for anymore value.
cout<<"Break From Loop \n";
Assuming your question is "How do I resume input after the stream state has been set?" then there is a simple explanation:
The while loop in which you performed the extraction terminated only until the extraction failed; this also includes when the stream reaches the end of the input stream (EOF). When that happens the eofbit will be set in the steam state (as well as the failbit). A stream can't be used for I/O when its stream state is set. In order to use it again, the stream state must be cleared. This is done using the member function clear(std::ios_base::iostate err = std::ios_base::goodbit).
std::cin.clear();
That call will clear the bits in the stream state and assign them to 0 (std::ios_base::goodbit). After this call the stream can be used for I/O again.
This is assuming the stream read all the characters until it reached EOF. It's not sufficient for a pervious read that terminated upon the acquisition of invalid data. One would also have to ignore() the remaining characters.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
I'm practicing with c string / pointers and can't solve this simple problem. cin.getline() isn't prompting user input for the first iteration, but does so for the consecutive strings. (I arbitrarily chose 10 as the char limit).
Am I overlooking something extremely simple?
void getStrings() {
int num;
cout << "How many strings? ";
cin >> num;
const int numStrings = num;
char** stringSet = (char**) malloc(numStrings * sizeof(char*));
for (int i = 0; i < numStrings; i++) {
*(stringSet + i) = (char*) malloc(10);
cout << "String " << i << ": ";
cin.getline(stringSet[i], 10);
cout << endl;
}
Setting aside the fact that it's generally inadvisable to use bare pointers in C++ when things like the standard library's std::string are available, you should not use malloc. For example: Instead of (char*) malloc(10), you should write new char[10] and remember to delete[] *(stringSet+i) at the end of your program.
That said, the line:
cin >> num
... extracts only the first number it comes across. It will fail (and cin will set its fail bit, and will need to be reset with cin.reset()) if it encounters any non-whitespace characters before it encounters a number.
But it stops extracting from the input after that. In your input stream is still whatever whitespace or other characters were still present in your input. For example, if you ran this program and typed "2 foobar" before pressing enter, it would immediately print:
String 1: foobar
String 2:
This is because the stream still contains "foobar\n".
In order to get the behavior you're looking for you will probably want to add this before your loop:
cin.ignore();
That will clear the stream of anything that's there.
cin >> num;
This will prompt the user for some input. Assuming the user does what's expected of them, they will type some digits, and they will hit the enter key. The digits will be stored in the input buffer, but so will a newline character, which was added by the fact that they hit the enter key. cin will parse the digits to produce an integer, which it stores in the num variable. It stops at the newline character, which remains in the input buffer. Later, you call getline, which looks for a newline character in the input buffer. It finds one immediately, so it doesn't need to prompt the user for any more input. So it appears that the first call to getline didn't do anything, but actually it did.
What do you mean by " isn't prompting user input for the first iteration"? I read that to mean "isn't printing the prompt for the input of the first string", but based on your code, I think it means "is printing the prompt for the input of the first two strings before it reads input."
cin >> num reads a number, the whole number, and nothing but the number. It does not read whatever follows the number, like a newline. So the first getline reads the newline character which you've already typed.
By the way, you should use cerr instead of cout for user prompts.
cout should be reserved for actual output. That makes scripting much easier, because you can redirect cout independent of cerr, and because you don't want to capture prompts in the program results anyway.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Need help with getline()
I'm trying to use the getline function in conjunction with cin to get input from the keyboard but my code skips over the getline statement and instead proceeds to cin function below. Here is my code and a screenshot of what is happening.
void addmovie(ofstream& MovieContentsFile) {
string movieTitle;
int movieQuantity;
cout << " \n Add Movie Selected \n " << endl;
cout << "Please type in the movie title and press enter \n" << endl;
getline(cin,movieTitle, '\n');
cout << "Movie: " << movieTitle << "Please type in the amount of copies we have of this movie \n " << endl;
cin >> movieQuantity;
I'd appreciate an explanation of why this is happening and how I can avoid it in the future
cin >> something leaves the trailing newline in the buffer, which would be ignored by the next cin >> something_else (presumably this is how you read the menu option). However, getline gets everything up to and including the next newline in the buffer, not ignoring whitespace. I.e. it gets nothing in this case (well, just the newline character).
Generally it's best not to mix use of both, it can get kinda messy.
Edit: To clarify, getline will remove that last newline from the buffer, but won't store it in your string.
It's because the newline character is still in the buffer so when it gets to the getline it sees it and skips over it. To avoid this you could place something like cin.ignore(25, "\n") on the line before. This will ignore 25 characters until it gets to the newline and then it takes that as well.
I am having a problem, but I cannot figure out what I'm doing wrong. I'm not sure if it's a problem with my loop, or the cin buffer is not being cleaned. I am doing a program that transforms a C-style string to uppercase, however if the user enters more than 11 characters, then the function should only display the first 11, and anything after that should not be displayed.the problem is that if I enter more than 11 characters, then my loop never stops and keeps telling the user that the answer entered is invalid and if he would like to enter a new string.
The issue comes from when you're trying to clear your buffer. When you return from cStringToUpper there are still extra characters in your buffer, but you're immediately looking for y/q.
You give cin.getline a buffer 12 long so it will only take that many characters, the rest are still in the buffer. If you instead use
string str;
cin.getline(str)
Then you will get the whole line, then you can crop it at 11 characters. Not 100% on the cin-syntax but you get the idea.
Or move the ignore-part above
cin >>cont;
to ignore the extra characters that way.
cin >> cont;
cout << "\n" << endl;
cin.ignore(200,'\n');
should be
cin.ignore(200,'\n');
cin >> cont;
cout << "\n" << endl;
You may correct your program by modifying your cStringToUpper fn. something like:
...
int loopCount;
char buffer[256];
cin.getline(buffer,256);
strncpy(letters, buffer, 11);
//letters[11]= '\0';
cout << "\n" << endl;
...