我有一个名为 file.txt 的文件
1 2 3
ugjfnuwd
gjufjfg
我想提取该文件“1 2 3”的第一行并将其转换为 c++ 中的数组,因此最终结果将如下所示
[1, 2, 3]
我已经试验和研究了大约 2 个小时,但进展甚微。请帮忙
我会将这一行读入 a std::string,然后使用 anstd::istringstream来解析行外的整数,按照这个一般顺序:
// open the input file:
std::istream infile("file.txt");
// read in the line
std::string line;
std::getline(infile, line);
// put the line into a stringstream
std::istringstream parser(line);
// initialize the vector from the numbers in the stringstream:
std::vector<int> numbers{ std::istream_iterator<int>(parser), {} };
// print out the result, one number per line:
for (int i : numbers)
std::cout << i << "\n";
像正常一样将第一行读入一个字符串,然后将字符串拆分为一个数组,分隔符是空格字符。