xdavidliu
xdavidliu

Reputation: 3052

cannot use cin twice, also cin.clear and cin.ignore don't work

I'm new to C++ programming, and I've come upon a roadblock. Here's my code:

#include <iostream>
using namespace std;

int main(){

    int sum = 0, a;
    cout << "enter first set of numbers:";
    while(cin >> a) sum += a;
    cout << "first sum = " << sum;
    cin.clear();
    cin.ignore( numeric_limits<streamsize>::max(), '\n');

    sum = 0;
    cout << "enter second set of numbers:";
    while(cin >> a) sum += a;
    cout << "second sum = " << sum;
}

I'm trying to sum two sets of numbers that I input at the command line. The problem is that when I hit ctrl-d to terminate my first set of numbers, it skips the second set of cin's. Most of the pages I find elsewhere on the internet tell me to use cin.clear and cin.ignore. I've tried that and it still doesn't work. This page question concerning cin.clear() even seems to have the same problems. However, the fixes they suggest don't work for me.

Does this code above work for anyone else?

Upvotes: 3

Views: 1992

Answers (3)

Jae Mun Choi
Jae Mun Choi

Reputation: 129

//Use stringstream ^^ for multiple user input

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

int main (void)
{
    string mystr;
    float price = 0;
    int quantity = 0;

    cout << "Enter price: ";
    getline (cin, mystr);
    stringstream(mystr) >> price;
    cout << "Enter quantity:";
    getline (cin, mystr);
    stringstream(mystr) >> quantity;
    cout << "Total price: " << price*quantity << endl;

    return 0;

}

Upvotes: 0

Aage Torleif
Aage Torleif

Reputation: 2013

You can use Ctrl-D, you just need to have your loop in another thread. So Ctrl-D, kills the thread, then returns to your main function, then you can start another thread. It'd not the best solution, but it can work, http://codebase.eu/tutorial/posix-threads-c/

Upvotes: -1

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 154045

When you use Ctrl-D you terminate the input stream: there is no further character coming from std::cin. Even clearing the stream doesn't help: you have told the stream it is at its end. You can't reopen it. However, clear()ing the stream and using ignore() is the solution to your problem!

You need a different indicator that one set of values is done. The easiest is to use a non-digit character or string: trying to read something which isn't an int will cause the stream to go into failure mode [without closing the stream]. That is, you read until the conversion fails, clear() the stream, and ignore() everything up to the end of the line.

Your code should already do that: instead of using Ctrl-D just enter, e.g., x.

Upvotes: 2

Related Questions