我想通过读取文件来打印整数值。
代码:
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/