如何逐行阅读 [英] How to read line by line
问题描述
我只是C ++的初学者,所以请不要轻易判断我. 也许这是一个愚蠢的问题,但我想知道.
i am just a beginer in c++ so please do not judge me hard. Probably this is silly question but i want to know.
我有一个这样的文本文件(总会有4个数字,但行数会有所不同):
i have a text file like this(there always will be 4 numbers, but the count of rows will vary):
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个数字执行某些功能.我怎样才能做到这一点? 就我而言
And here is what i want to do: i want to read this file line by line and put each number into variable. Then i will do some functions with this 4 numbers and then i want to read the next line and again do some functions with this 4 numbers. How can i do that? This is as far as i am
#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;
}
但是像这样,我正在将整个文件读入数组,但是我想逐行读取它,执行我的功能,然后读取下一行.
but like this i am reading whole file into array, but i want to read it line by line, do my function and then read the next line.
推荐答案
对于从文件中读取数据,我发现字符串流确实很有帮助.
For reading data from file I find the stringstream really helpful.
这样的事情怎么办?
#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;
}
这篇关于如何逐行阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!