void AlterNameByNum ()
{
int count =0;
int year;
int month;
int day;
int findnum;
string alteryear;
string altermonth;
string alterday;
bool find = false;
cout<<"请输入要修改学生的学号";
cin>>findnum;
cout<<"请输入要修改学生的出生日期";
cin>>alteryear>>altermonth>>alterday;
ifstream infile ("d:\\student.txt", ios::in);
if(!infile)
{
cout<<"文件打开失败"<<endl;
}
ofstream outfile ("studentcopy.txt" , ios::app) ;
if (! outfile)
{
cout<<"文件打开失败"<<endl;
exit (0);
}
while (! infile.eof ())
{
infile>>num>>name>>year>>month>>day;
if(num!=findnum)
{
outfile <<num<<" "<<name<<" "<<year<<" "<<month<<" "<<day<<endl;
}
else
{
outfile <<num<<" "<<alteryear<<" "<<altermonth<<" "<<alterday<<" "<<name<<endl;
find = true;
cout<<"已经修改该学生"<<endl;
}
infile.get ();
if (infile.peek () =='\n') break;
}
if(! find)
{
cout<<"查无此人"<<endl;
}
infile.close ();
outfile.close ();
remove (" d:\\student.txt" ) ; //删除文件
rename ("studentcopy.txt", "student.txt");
}
private:
int num;
string name;
Date birthday;
};
这段代码为什么不能实现修改学生的出生日期
,如果要修改应该怎么修改,写出修改后的代码
关于#c++#的问题:这段代码为什么不能实现修改学生的出生日期
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
关注 引自免费微信小程序:皆我百晓生
从提供的代码片段来看,存在几个关键问题导致无法正确修改学生的出生日期。主要问题在于数据类型不匹配、文件读写逻辑以及变量作用域。下面将详细分析并提供修正方案。
问题1: 数据类型不匹配
在代码中,
year
,month
, 和day
被定义为int
类型,而输入时却尝试使用string
类型的alteryear
,altermonth
, 和alterday
进行替换。这会导致类型转换错误,因此修改不会按预期进行。解决方案:
确保所有日期相关的变量都是同一种类型。如果希望保持日期为字符串格式,那么在读取和写入文件时也应使用字符串类型。
代码修正示例:
// 将 int year, month, day 更改为 string std::string year, month, day; // 在读取文件时,使用 >> 来读取字符串 infile >> num >> name >> year >> month >> day; // 在写入文件时,使用 << 来输出字符串 outfile << num << " " << name << " " << year << " " << month << " " << day << std::endl;
问题2: 文件读写逻辑
当前代码中的逻辑在处理文件读写时可能存在一些问题。特别是,在比较
num != findnum
后立即进行写操作,可能会跳过应该被修改的记录。此外,while
循环的终止条件使用了eof()
方法,这通常不是一个好的实践,因为它可能导致读取最后一行数据时出现问题。解决方案:
- 使用更可靠的循环终止条件。
- 确保在比较前读取所有字段。
修正后的文件读写逻辑:
std::string line; std::getline(infile, line); // 读取一行 while (std::getline(infile, line)) { std::istringstream iss(line); iss >> num >> name >> year >> month >> day; if (num != findnum || !find) { outfile << num << " " << name << " " << year << " " << month << " " << day << std::endl; } else { outfile << num << " " << name << " " << alteryear << " " << altermonth << " " << alterday << std::endl; find = true; } }
问题3: 变量作用域
当前代码中的一些变量(如
num
,name
,year
,month
,day
)被声明为类的私有成员。这意味着它们在函数外部也有生命期,这可能不是预期的行为。通常,这些变量最好作为函数的局部变量。总结
为了确保代码能够正确地修改学生的出生日期,建议按照上述修改进行调整。这样可以确保数据类型的正确性,优化文件读写的逻辑,并管理好变量的作用域。如果还有其他具体疑问,欢迎继续提问。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥35 navicat将excel中的数据导入mysql出错
- ¥15 rt-thread线程切换的问题
- ¥20 python忆阻器数字识别
- ¥15 高通uboot 打印ubi init err 22
- ¥20 PDF元数据中的XMP媒体管理属性
- ¥15 R语言中lasso回归报错
- ¥15 网站突然不能访问了,上午还好好的
- ¥15 有没有dl可以帮弄”我去图书馆”秒选道具和积分
- ¥15 semrush,SEO,内嵌网站,api
- ¥15 Stata:为什么reghdfe后的因变量没有被发现识别啊