【发布时间】:2020-04-29 08:38:02
【问题描述】:
我必须计算保存在文件中的数字的平均值,但出现“+”运算符错误。有什么问题?
int main()
{
int a;
fstream File;
string Line;
File.open("file.txt", ios::in);
if (File.is_open()){
while(!File.eof()) //.eof -> End Of File
{
File>>Line;
a=a+Line;
cout<<Line<<"\n";
cout << a;
}
}
else{
cout << "File open error";
}
File.close();
return 0;
}
【问题讨论】:
-
Line是一个字符串。您不能将int a添加到字符串中。根据您的用例,首先使用stoi()、stof()等将字符串转换为数字。 -
哦,当然,谢谢
-
@Roy2511 或者,只需将字符串替换为 int 即可。
>>可以直接读入int,不需要手动 -
@RemyLebeau 当然,为什么不呢。