如何用其总和替换文件中的数字?
How to replace a number in a file with its sum?
我想编写一个程序,获取文件中的整数,将其与输入数字相加,然后用求和结果替换文件中的前一个整数。我认为下面的代码可以工作,但是无论我输入的整数是什么,文件中写入的 0 仍然是 0。我做错了什么?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream arq;
arq.open("file.txt");
int points, total_points;
cin >> points;
arq >> total_points;
total_points += points;
arq << total_points;
}
您可以尝试分别读写输入文件,如下图:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream arq("file.txt");
int points=0, total_points=0;
cin >> points;
arq >> total_points;
total_points += points;
arq.close();
ofstream output("file.txt");
output << total_points;
output.close();
}
上面程序的输出可见here.
由于您已打开文件进行读写,因此需要在将新值写入文件之前将输出位置指示器设置为位置 0。
示例:
#include <cerrno>
#include <fstream>
#include <iostream>
int main() {
const char* filename = "file.txt";
if(std::fstream arq(filename); arq) {
if(int total_points; arq >> total_points) {
if(int points; std::cin >> points) {
total_points += points;
// rewind the output position pointer to the start of the file
arq.seekp(0);
arq << total_points;
}
}
} else {
std::perror(filename);
}
}
请注意,如果您想将 更短的 值写入文件,您最终可能会得到一个如下所示的文件:
之前:
123456
将45
写入文件后:
453456
因此,我推荐 中的方法,该方法在写入文件之前截断文件。
我想编写一个程序,获取文件中的整数,将其与输入数字相加,然后用求和结果替换文件中的前一个整数。我认为下面的代码可以工作,但是无论我输入的整数是什么,文件中写入的 0 仍然是 0。我做错了什么?
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream arq;
arq.open("file.txt");
int points, total_points;
cin >> points;
arq >> total_points;
total_points += points;
arq << total_points;
}
您可以尝试分别读写输入文件,如下图:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ifstream arq("file.txt");
int points=0, total_points=0;
cin >> points;
arq >> total_points;
total_points += points;
arq.close();
ofstream output("file.txt");
output << total_points;
output.close();
}
上面程序的输出可见here.
由于您已打开文件进行读写,因此需要在将新值写入文件之前将输出位置指示器设置为位置 0。
示例:
#include <cerrno>
#include <fstream>
#include <iostream>
int main() {
const char* filename = "file.txt";
if(std::fstream arq(filename); arq) {
if(int total_points; arq >> total_points) {
if(int points; std::cin >> points) {
total_points += points;
// rewind the output position pointer to the start of the file
arq.seekp(0);
arq << total_points;
}
}
} else {
std::perror(filename);
}
}
请注意,如果您想将 更短的 值写入文件,您最终可能会得到一个如下所示的文件:
之前:
123456
将45
写入文件后:
453456
因此,我推荐