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

标签 c++ ifstream

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

代码:

    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/

相关文章:

c++ - 在哪里可以找到具有多个源文件 (> 15) 的中型开源 C(也包括 C++)程序

c++ - 无法读取输入文件 ifstream

c++ - ifstream eof 循环读入条件表达式中的变量?

C++ 前向引用

c++ - 在 Visual C++ 中创建 "Add New Item Wizard"

android - 我可以在 Android NDK 中使用 ifstream 来访问资源吗?

C++:从文本文件中读取

c++ - 使用 token 仅解析 csv 文件中的特定列

c++ - 通过指针与数组中的索引链接结构图

c++ - 在 linux 上的 c++ 代码中通过 sendfile() 复制的速度是多少?