I am new to c++.My aim is to read a file containing all integers, like
1 2 3\\n 1 3 4\\n 1 2 4\\n
and
1,2 3,4 5,6\\n 1,3 3,4 3,5\\n 1,3 3,4 4,2\\n
I could use getline to read them, but how could I split it into an integer array. Like array[3]={1,2,3}
and array2={1,2,3,4,5,6}
for the first line reading result? Sorry I forgot to mention that I was trying to not use the STLs for C++
You can do it without boost spirit
// for single line:
std::vector<int> readMagicInts(std::istream &input)
{
std::vector<int> result;
int x;
while(true) {
if (!(input >> x)) {
char separator;
input.clear(); // clear error flags;
if (!(input >> separator >> x)) break;
if (separator != ',') break;
}
result.push_back(x);
}
return result;
}
std::vector<std::vector<int>> readMagicLinesWithInts(std::istream &input)
{
std::vector<std::vector<int>> result;
std::string line;
while (std::getline(input, line)) {
std::istringstream lineData(line);
result.push_back(readMagicInts(lineData));
}
return result;
}
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.