gpt4 book ai didi

C++ : Read form text file and convert to int problem?

转载 作者:行者123 更新时间:2023-11-30 04:37:18 24 4
gpt4 key购买 nike

我有从 marks.txt 文件中读取的代码。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int main () {
string name,result;
int number1;
ifstream myfile ("marks.txt");
if (myfile.is_open())
{
while ( !myfile.eof() )
{
getline (myfile,name,'\t');
getline (myfile,result,'\t');
stringstream(result) >> number1;
cout << number1;


}

myfile.close();

}

else cout << "Unable to open file";

return 0;
}

我的 marks.txt 文件包括:

john 20

但是当我运行程序时。 Number1 输出为 36。如何将结果字符串正确转换为 int??

最佳答案

请注意,您将 \t(制表符)作为分隔符传递给 getline。您确定在输入文件中使用了制表符吗?如果您使用空格或任何其他字符,所有输入都将进入 name 并且您的 result 将为空,这将使 number1 未定义.我怀疑这就是你莫名其妙得到 36 的原因。

关于C++ : Read form text file and convert to int problem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3946260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com