如何逐行阅读

How to read line by line

本文关键字:逐行 何逐行      更新时间:2023-10-16

我只是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] = ''; 
        for (int i = 0; array[i] != ''; i++)
        {
            cout << array[i];
        }
    }
    else
    {
        cout << "File could not be opened." << endl;
    }
    return 0;
}

但是像这样,我将整个文件读取到数组中,但我想逐行读取它,执行我的函数,然后读取下一行。

对于从文件中读取数据,我发现字符串流非常有用。

这样的事情呢?

#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;
}