简体   繁体   中英

read data up to '\n'

I have an input file for my program that stores the values to use for two parameters.

# X parameter values to use
10 20 30 40
# Y parameter values to use
5

The number of the values are not fixed but is the client that choose how many values to use (in this example 4 for X and 1 for Y (could be 0 too)). If I do an

ifstream in("input.in");
int value;
in >> value >> value >> ...

the program don't stops at the end of the line and reads obviously also Y line for X values when the X line ends. How to stop reading at the end of the line? I want to read values untill in found the '\\n'. Thanks!

std::string line;
std::getline(in, line);

Now you have the line as a string ( #include <string> ) and need to parse it. You can do it the same way as before by making use of std::istringstream ( #include <sstream> ).

std::istringstream iss(line);
while (iss >> value) // read until failure
{
    // process value
}

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