Visual Studio 2022运行C++程序时文件内容被删除的问题求助
问题分析与解决:程序运行清空文件且读取失败
核心问题原因
1. 不必要的文件写入操作清空了内容
你代码里定义了ofstream dout并执行了dout.open("age.txt");——默认情况下,ofstream打开文件时会自动截断(清空)原有内容,哪怕你没有往文件里写入任何数据,只要执行了打开操作,文件就会被清空。而你的作业只需要读取文件内容,完全不需要这个写文件的流,这就是每次运行程序age.txt里的"25"消失的根本原因。
2. 读取逻辑错误导致内容为空
你在读取时连续执行了:
getline(din, age); din >> age;
第一个getline已经把文件里的"25"读取到age中,此时文件指针已经移动到文件末尾。紧接着的din >> age尝试从文件末尾继续读取,无法获取任何内容,会将age重置为空字符串,最终导致输出显示为空。
修复步骤与代码
步骤1:删除多余的写文件流
去掉所有和ofstream dout相关的代码,包括定义、打开、关闭操作。
步骤2:修正读取逻辑
只保留一种读取方式即可,因为文件中只有单个数字,用din >> age更简单直接。
修复后的完整代码:
#include<iostream> #include<string> #include<fstream> using namespace std; int main() { ifstream din; string inpFileName; string age; // The user's age // Prompt for the age: cout << "Please provide the file containing your age" << endl << endl; cin >> inpFileName; din.open(inpFileName.c_str()); // File extension is arbitrary if (din) { // Read the age: din >> age; // Output the age cout << "Your age is: " << age << " years." << endl; } else cout << inpFileName << " was not found. " << endl; din.close(); system("pause"); return 0; }
额外说明
如果你的age.txt中内容是带换行的(比如"25\n"),用getline(din, age)也可以正常读取,但不要同时混用getline和>>读取同一个文件流,避免指针位置混乱。
内容的提问来源于stack exchange,提问作者Walnut_Meat
相关产品推荐
相关产品推荐

