如何逐行读取

4

我是一名C++初学者,请不要太苛刻地评价我。

也许这个问题很傻,但我想知道。

我有一个这样的文本文件(总会有4个数字,但行数会有所变化):

5 7 11 13
11 11 23 18
12 13 36 27
14 15 35 38
22 14 40 25
23 11 56 50
22 20 22 30
16 18 33 30
18 19 22 30

这是我想要做的事情: 我想逐行读取这个文件,并将每个数字存入变量中。然后我将对这4个数字进行一些函数处理,接着我想读取下一行,并再次对这4个数字执行一些函数操作。我该怎么做呢? 目前我只完成了这些。

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    int array_size = 200;
    char * array = new char[array_size];
    int position = 0;

    ifstream fin("test.txt");

    if (fin.is_open())
    {

        while (!fin.eof() && position < array_size)
        {
            fin.get(array[position]); 
            position++;
        }
        array[position - 1] = '\0'; 

        for (int i = 0; array[i] != '\0'; i++)
        {
            cout << array[i];
        }
    }
    else
    {
        cout << "File could not be opened." << endl;
    }
    return 0;
}

但是现在我的代码是将整个文件读入到数组中,我想逐行读取并处理每一行。


1个回答

2

对于从文件中读取数据,我发现stringstream非常有用。

这个怎么样?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

int main()
{
  ifstream fin("data.txt");
  string line;

  if ( fin.is_open()) {
    while ( getline (fin,line) ) {
      stringstream S;
      S<<line; //store the line just read into the string stream
      vector<int> thisLine(4,0); //to save the numbers
      for ( int c(0); c<4; c++ ) {
        //use the string stream as a new input to put the data into a vector of int    
        S>>thisLine[c]; 
      }
      // do something with these numbers
      for ( int c(0); c<4; c++ ) {
        cout<<thisLine[c]<<endl;
      }  
   }
}
else
{
   cout << "File could not be opened." << endl;
}
return 0;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接