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');
Related
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 5 years ago.
Improve this question
I came across a question whereby you are told there will be unspecified number of queries hence you got to keep on taking input for this unspecified number of queries
all i know is that in c++ or even in another programming language, when the program needs to take unspecified number of input, we prompt the user to enter a certain value which will be used to terminate the infinite loop e.g
for (;;)
{
cout<<"enter 0 to stop taking input"<<endl;
int value;
cin>>value;
if (value==0)
{break;}
}
my question is how will i handle the question stating the input will be unspecified and its in an online environment
for this kind of problem you will use a loop control variable and a while loop for user input validation
while loop is use for input validation while for loop is use for specific
number of times only and it is not really suggested for unknown number of times
same with while loop, do while loop can also perform input validation the
only difference is, it will prompt the user first before evaluating the test condition
int myNum; // this is the loop control variable
cout << "enter a number, enter 0 to stop taking input " << endl;
cin >> myNum;
while(myNum!=0)
{
cout << "cograts you did not enter zero digit" << endl;
cin >> myNum;
}
use while (cin >> a) :
to see how if it works create an input file 1.in and write a bunch of numbers in it, then pipe it to your executable fle ./a.out <1.in
#include <iostream>
using namespace std;
int main() {
int a;
while (cin >> a) {
cout << a << "\n";
}
return 0;
}
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.
It must be that I'm tired but I can't seem to figure out why my program will not read my cin values for init and end which is supposed to be a start and an end point for my program. The way its setup for input is the first line is the amount of cases then there will be a new line which will be a string then on the next line there will be two integers separated by a space so I feel the way I built it is correct but when I debug the code the values for init and end never change whether I initialize the variable or not.
int case_count;
string name;
int init = 0;
int end = 0;
cin >> case_count;
cin.ignore(numeric_limits<::streamsize>::max(),'\n');
for (int i = 0; i < case_count; ++i) {
cout << "Case " << i << "\n";
getline(cin, name);
cin.ignore(numeric_limits<::streamsize>::max(), '\n');
cin >> init;
cin >> end;
Example input
3
flap
1 3
swoop
0 9
flip
0 6
Its making it hard to continue with the rest of the code.
The problem is that you call ignore in the loop. The problem with this is that std::getline extracts (and throws away) the newline character, meaning your ignore call in the loop will read and discard the next line (the one with the two numbers).
Besides that, when using the input operator to read numbers or strings, the operator will skip leading white-space, so even if getline didn't read the newline, it would still have worked without the ignore call.
However, there is a newline left over in the input stream after you read the numbers, and the next iteration the std::getline call will pick up that newline and then name will be empty, so you should, as suggested by M.M in a comment, move the ignore call to last in the loop.
This question already has answers here:
Trying to use a while statement to validate user input C++
(4 answers)
Closed 7 years ago.
There is a loop i want to run and check for valid input, if not valid jump out the itteration and start at the beginning of the loop where i ask for input.
close = false;
int direction
while (!close){
if (!(cin >> direction)){
cout << "not valid: " << endl;
continue;
}
close = true;
}
However when I run it I can only enter the direction one time and not reenter it when continue is reached. How can I end a itteration and let the user retry.
When adding the variable to the while loop and remove from above the while loop (it's local to the while loop and destroyed outside than right?) like
while (!close){
int direction;
////
}
it also dosn't work. I know the whole part of code could be better but I just started with c++ and am trying to understand why it dosn't work like i expect.
Why not use a while loop?
while(! (cin >> x)) {
cout << "invalid input " << endl;
}
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.