C++:读取数值数据直到



无论如何都可以获得数值数据,直到新行n

我知道getline()函数在达到n之前一直有效,但它是一个字符串函数,所以当我需要从文件中收集数字输入时,我不知道如何使用它。

我需要能够做到这一点,因为假设我在这样的文件中有数字数据:

23 42 523 423 53
13 24 242 24 23 23 523 52
42 24 12

如果我必须收集每行的总和,那么我必须能够知道给定行何时结束(何时达到n),如果与我上面提供的示例不同,要读取的行数未知,则确实如此。

您只需检查 int 之后的下一个字符即可执行任务!

#include <iostream>
#include <string>
#include<fstream>
using namespace std;
int main()
{
ifstream in("File.txt");
int count = 0;
int temp = 0;
char ch = '';
int i = 1;
while (!in.eof())
{
while (ch != 'n')
{
in >> temp;
count = count + temp;
in.get(ch);
if (in.eof())
break;
}
cout << "Line : " << i << " Sum : " << count;
if (!in.eof())
ch = '';
count = 0;
i++;
}
system("pause");
return 0;
}

另一种方法是读取 2D 数组中的数据并将其每一行求和。

int arr[n][m];
int temp=0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
in>>arr[i][j];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
temp=temp+arr[i][j];
}
cout<<temp;
temp=0;
}

最新更新