C++用户输入写入TXT文件异常:读取结果为0 0 0求助
问题分析与修复方案
你的程序输出始终是0 0 0,核心问题出在参数传递方式,还有其他几处代码逻辑错误,下面逐一说明并修复:
主要问题点
- 值传递导致主函数变量未更新:
getDate函数的day、month、year是值传递,函数内部修改的只是局部变量副本,主函数里的原始变量始终是初始化的0。必须改成引用传递才能让函数修改主函数的变量。 - return语句无效:
return day, month, year;是逗号表达式,只会返回最后一个值year,而且函数返回类型是int,根本没法返回三个值,何况主函数也没接收这个返回值,完全没用。 - 错误递归调用main:在
getDate里调用int main();不符合C++规范,标准不允许递归调用main函数,应该用循环实现重新输入的逻辑。 - 代码执行顺序错误:
main函数里return 0;之后的system("pause>0");永远不会执行,要放到return之前。
修复后的完整代码
#include "iostream" #include "string" #include "fstream" #include <cctype> // 用于tolower函数 /* ********************@ Salary Calculator @******************** * Store the date of the day - 01.12.22 example V * Store Name of the day * Store Number of hours of day * */ using std::cout; using std::cin; using std::string; using std::endl; using std::ios; using std::ofstream; using std::fstream; void getDate(int& day, int& month, int& year) { char key; do { cout << "\nEnter the Day : "; cin >> day; cout << "\nEnter the Month : "; cin >> month; cout << "\nEnter the Year : "; cin >> year; cout << "\nDate Entered : " << day << "." << month << "." << year; cout << "\nWould You Like To Change The Date ? (Y/N) "; cin >> key; // 兼容大小写输入 key = tolower(key); } while (key == 'y'); cout << "\nDate Saved"; } void writeToFile(int day, int month, int year) { ofstream Data; Data.open("Data.txt", ios::app); Data << day << endl; Data << month << endl; Data << year << endl; Data.close(); } void readFromFile() { fstream Data; Data.open("Data.txt", ios::in); if (Data.is_open()) { string line; while (getline(Data, line)) { cout << line << '\n'; } } Data.close(); } int main() { int day{}, month{}, year{}; getDate(day, month, year); writeToFile(day, month, year); readFromFile(); system("pause>0"); return 0; }
修复说明
- 把
getDate的参数改成引用int& day, int& month, int& year,这样函数内部的修改会直接作用于主函数的变量。 - 用
do-while循环替代调用main,实现重复输入日期的逻辑,同时加上tolower(key)兼容用户输入大写Y的情况。 - 移除无效的return语句,把
getDate改成void类型,因为不需要返回值,直接通过引用修改主函数变量。 - 调整
system("pause>0");的位置,放到return 0;之前,确保程序结束前会暂停。
内容的提问来源于stack exchange,提问作者matan izhak
相关产品推荐
相关产品推荐

