题目:
现在项目中有一个文件,其中全是数字,现在求其中的和
代码如下:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
fstream OpenFile("test.txt");
int arr[20];
char ch;
int i = 0;
while (!OpenFile.eof()) {
OpenFile.get(ch);
int a = (int)ch;
arr[i] = a-48;
i++;
}
int sum=0;
for (size_t i = 0; i < 20; i++)
{
sum += arr[i];
}
cout << "文件中数字的和为:"<<sum << endl;
system("pause");
return 0;
}
输出效果:
C++中文件的读取操作:
在此提两点比较简单的操作:
先: #include
- 读取并转化为数字:
fstream OpenFile(“test.txt”);
while (!OpenFile.eof()) {
OpenFile.get(ch);
int a = (int)ch;
arr[i] = a-48;
i++;
}
*写入一个文件:
ofstream ShuRuFile(“abc.txt”);
ShuRuFile << “Hello,world!”;
ShuRuFile.close();
写入文件结果: