简体   繁体   中英

Is it possible to use cin and getline one after the other on the same line?

My input is a line such as:

12345 14 14 15 15

Where 12345 is a student's id number that can vary in size, and the rest of the input is the student's scores. From this line, I am trying to store the id into one variable and the scores, which I will then convert into an int array, into another. I tried doing something like this:

int id;
std::string scores;
std::cin >> id;
std::cin.ignore(' '); //ignore the space after the id number
std::getline(std::cin, scores); //store the rest of the line into scores

This doesn't seem to be working though. Is something like this possible?

I thought I could instead use substring to separate the two portions, but since the length of the id number can vary, I don't think I'd be able to.

What would be the best way to tackle what I'm trying to do? Sorry if this is kind of trivial; I'm still a beginner in C++.

std::basic_istream::ignore() does not do what you think it does. If you consult a suitable reference , you'll find that the first parameter is the number of characters to ignore, and the second one is the delimiter. You're basically asking it to ignore 32 characters (since 32 is the ASCII code of space).

You want this instead:

int id;
std::string scores;
std::cin >> id;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' '); //ignore all characters until a space is found
std::getline(std::cin, scores); //store the rest of the line into scores

Alternatively, if you know there will always be just one space after it, simply call std::cin.ignore(); without arguments, since that implies ignoring 1 character.

I'm not sure what isn't working but I certainly wouldn't use ignore() to ignore separating space. Instead, I'd just use

std::getline(std::cin >> id >> std::ws, scores);

The manipulator std::ws will ignore all whitespace.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM