gpt4 book ai didi

c++ - 无法打印所有整数值

转载 作者:行者123 更新时间:2023-11-30 01:13:51 26 4
gpt4 key购买 nike

我想通过读取文件来打印整数值。

代码:

    int temp;
char* trainname;
trainname="dfg.txt";
ifstream trainfile;
trainfile.open(trainname);
if(!trainfile){
cout<<"Cannot open file!"<<'\n';
exit(1);
}
while(trainfile >> temp)
cout << temp << " ";
trainfile.close();

dfg.txt: 1 2 we er rf 5

输出:1 2

问题是它不打印5

最佳答案

先读取一个临时字符串,然后使用std::stoi尝试从中解析一个整数,如果成功,输出它:

std::string temp;

while(trainfile >> temp) {
try {
std::cout << std::stoi(temp) << " ";
}
catch(const std::invalid_argument&) {
// not a valid number
}
}

关于c++ - 无法打印所有整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31089845/

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