简体   繁体   中英

Reading input with varying number of ints each line in C++

I am trying to read in user input from the console. The data is as such

3
3 100
5 100
6
9 200
6
9

Where the first line represents N, and there are 2*N entries following it. How would I decide whether a line has two int inputs or just one.

I thought about implementing getline, but that just gives me the whole line, and it gives me a string with a space in between.

Thanks

I always use getline and parse the string myself. This gives you the most flexibility and is pretty much a requirement when you get to the point that you want to do error handling.

It's not that hard to split a string into pieces based on a common delimiter (like a space). And writing that code is good practice for you.

std::vector<std::string> splitAt(const std::string &input, const std::string &delim) {
    std::vector<std::string> vec;
    ...
    return vec;
}

Implement that, and you're golden. The rest of the problem solves itself, and you can use it over and over.

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