c++ - 将由空格分隔的文件读入动态数组C++

标签 c++

您好,我将从文件中读取并将用空格分隔的数字放入不同的数组中。 要读取的示例文件

15
10 2
20 1
30 1

这是我做的

    while(!file.eof()){ 
        file>>first[count++];

    }

通过这样做,我逐行读取,但我想读取直到出现空白并将空白之后的数字放入不同的数组中。 结果数组将如下所示(假设 first 和 second 是动态整数数组)

first={15,10,20,30}
second ={0,2,1,1}

最佳答案

你应该使用 string streams .

#include <sstream>
...

string line;
while(getline(file, line))
{
   istringstream iss(line);
   int firstNumOnLine, secondNumOnLine.
   iss >> firstNumOnLine;
   first.push_back(firstNumOnLine);
   if(iss >> secondNumOnLine)
   {
        //... 
        second.push_back(secondNumOnLine)
   }
   else
   {
       //... there was no second number on the line.
       second.push_back(0);
   }
}

这里,firstsecond 被假定为 vector

关于c++ - 将由空格分隔的文件读入动态数组C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27018935/

相关文章:

c++ - vector<unique_ptr> 上的 is_copy_constructible 误报

c++ - C 而不是 C++ 中的对象工厂

c++ - OOLua编译错误

c++ - 在 c++ 中编译但在 c (gcc) 中编译时很复杂

c++ - 使用 GLEW、GLFW 和 g++ 编译在 OS X 10.10 下启用 OpenGL 4.1

c++ - 具有源子目录的单个顶级 makefile

c++ - 使用 libcurl 发送 post 请求

c++ - 带 Boost Spirit X3 的最小计算器

c++ - 模板递归区分 boot::tuple 中的数据类型

c++ - 无法将字符分配给字符串变量