使用getline从文件中抓取数据

时间:2014-10-15 20:38:10

标签: c++ file-io delimiter getline

所以我有一个包含多列数据的文件,如下所示:

1 2 3
4 5 6
7 8 9
etc...

我正在尝试将数据存储在向量中的while循环遍历此文件。但是当我使用分隔符来处理数据之间的空格时,它只读取第一行并停止。 while循环的代码如下:

while(getline(infile,content, ' '))
{
 double temp = atof(content.c_str();
 cout << "value storing is: " << temp << endl;
 data.push_back(temp);
}

使用上面的数据和这段代码我只得到“1 2 3”作为输出。所以我不确定我在哪里出错。

当我稍后处理数据时,数字所在的列也很重要。例如,while循环的每次迭代都会添加一个计数器,每次进入一个新行都将是另一个计数器,所以我可以计算出我有多少行,所以当我需要计算一些我可以使用的时候i% (columnNumber)获取该值。

感谢任何人可以解决我的情况。

1 个答案:

答案 0 :(得分:2)

这是因为新行之后没有空格。

这是文件的样子(std::getline()

1 space 2 space 3 newline 4 space 5 space 6 newline 7 space 8 space 9

我无法复制&#34; 1 2 3&#34;作为输出。当我运行你的代码时,我得到了

value storing is: 1
value storing is: 2
value storing is: 3
value storing is: 5
value storing is: 6
value storing is: 8
value storing is: 9

我的测试文件如下所示:

1 2 3
4 5 6
7 8 9

要解决此问题,请尝试执行this

之类的操作
int main()
{
    std::ifstream in("test");

    std::string content;
    std::vector<int> data;

    while (getline(in, content))
    {
        std::stringstream linestream(content);

        int value;
        // Read an integer at a time from the line
        while(linestream >> value)
        {
            // Add the integers from a line to a 1D array (vector)
            data.push_back(value);
            std::cout << "value storing is: " << value << std::endl;
        }
    }

}