如何逐行阅读
How to read line by line
我只是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;
}
相关文章:
- 如何创建一个具有可变行且每行有 3 列的 2D 数组?
- 为什么有一个指向此代码行(第 7 行)的"no matching call for function"错误?
- 检查数组行中每行C++是否始终存在相同的值
- QString 从行首或行尾修剪非空格字符
- 创建一个 2 行(不换行)的 QPushButton
- 代码行在两行后不起作用
- 使用 Qt 获取 csv 文件中两行之间所有行
- C++在不使用字符串流的情况下读取具有任意长度和格式的行的多行文件
- 在下一个行之前检测行尾
- 在换行的命令行中,取消//后面的空格的合理性
- 在 C++ 中逐行读取命令行的输出到字符串向量中
- 如何在QTableView/QbstractTableModel中使用多行文字/换行符
- C++捕获输入的命令行并逐行输出
- 在临时指针上使用"delete"后程序崩溃,即使只剩下新行和删除行?
- Qt-如何检测换行后的行数增加
- 可移植行结束符(换行符)
- 从tsv中读取100k+行的特定行数据,仅使用标准库
- 使用CFile检查换行符(换行字符)
- Ifstream如何使用c++从特定行开始读行
- 如何逐字读取文件的第一行,而将其他行作为逐行存储在变量中