无法打印所有整数值

时间:2015-06-27 14:33:06

标签: 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

4 个答案:

答案 0 :(得分:4)

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

std::string temp;

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

答案 1 :(得分:1)

while(trainfile >> temp)
    cout << temp << " ";

以上设置failbit上的trainfile会遇到任何不是空格或数字的字符。这终止了循环。这是我倾向于不使用可能在输入流上失败的格式化I / O的一个原因。我发现将文本作为文本(而非数字)读取更好,然后处理刚刚读取的字符串。例如,请参阅天顶的答案。

如果您坚持从输入流中执行所有操作,则需要一个外部循环来清除流failbit。例如,

while (! std::cin.eof())
{   
    while (std::cin >> temp)
    {
         std::cout << temp << " ";
    }
    std::cin.clear();
    std::cin.ignore();
}

如果输入文件包含1 2 we er rf 5,则上述内容将打印1 2 5。如果输入文件包含1 2 abc345def 6,则上述内容将打印1 2 345 6。请注意,天顶的方法将打印1 2 6。将345夹在abcdef之间的abc345def计为整数取决于您。


我建议使用天顶的解决方案。

<强>更新
上面将345解释为表示整数345def。两个Zenith的解决方案和上面的解释345都表示整数abc345def。对我而言,345def6.1都应该被拒绝为表示整数。我应该0x abc345def,但strtol没有错。 C标准库中有一个很好的工具#include <iostream> #include < fstream> #include <string> #include <cstdlib> int main () { std::ifstream trainfile("dfg.txt"); if (!trainfile) { std::cerr << "Cannot open file!\n"; exit(1); } std::string s; while(trainfile >> s) { char* end; long num = std::strtol (s.data(), &end, 0); if (!*end) { std::cout << num << " "; } } trainfile.close(); std::cout << "\n"; } ,可以很好地解析整数。它还指出了什么使解析停止。对于有效整数,它应该在输入字符串的末尾停止。有了这个,

kill()

答案 2 :(得分:0)

string temp;

if( '0' <= temp[0] &&  temp[0]<='9' )

      cout << temp << " ";

我认为它会起作用。

答案 3 :(得分:0)

这是您可以考虑的另一种方式 -

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

int main()
{
    ifstream trainname("dfg.txt",ios::in);
    string temp;

    getline(trainname,temp);
    stringstream str;
    str<<temp;

    int extract_int;

    while(getline(str, temp,' '))
    {
        if(stringstream(temp)>>extract_int)
            cout<<extract_int<<" ";
    }

    return 0;
}

或者根据 David Hammen 的回答,您可以通过以下方式解决问题 -

#include <iostream>
#include <sstream>
#include <fstream>

using namespace std;

int main()
{
    int temp;
    char* trainname;
    trainname="dfg.txt";
    ifstream trainfile;
    trainfile.open(trainname);

    if(!trainfile){
        cout<<"Cannot open file!"<<'\n';
        exit(1);
    }

    while (!trainfile.eof())
    {
        while (trainfile>>temp)
             cout<<temp<< " ";

        trainfile.clear();
        trainfile.ignore();
    }

    return 0;
}