简体   繁体   中英

How to read space separated input in C++ When we don't know the Number of input

I have read the data like the following

7
1 Jesse 20
1 Jess 12
1 Jess 18
3 Jess
3 Jesse
2 Jess
3 Jess

Here the 7 is the number of input lines and i have to read the space separated input in c++, How can i read those input where we don't know how to separate them. this line contains string and integers.

Here is one example, that uses operator>> and std::string :

int x;
std::string name;
int y;
int quantity;
std::cin >> quantity;
for (int i = 0; i < quantity; ++i)
{
    std::cin >> x;
    std::cin >> name;
    std::cin >> y;
}

The above will work for all lines that have 3 fields, but not with the lines without the last field. So, we'll need to augment the algorithm:

std::string text_line;
for (i = 0; i < quantity; ++i)
{
    std::getline(std::cin, text_line); // Read in the line of text
    std::istringstream  text_stream(text_line);
    text_line >> x;
    text_line >> name;
    // The following statement will place the text_stream into an error state if
    // there is no 3rd field, but the text_stream is not used anymore.
    text_line >> y;
}

The root cause is that the missing 3rd field elements will cause the first example to be out of sync because it will read the 1st column of the next line for the 3rd field.

The second sample of code makes the correction by reading a line at a time. The input operations are restricted to the text line and will not go past the text line.

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