0

我有以下 .txt 文件:

测试.txt

1,2,5,6

传入我通过命令行制作的一个小型 C++ 程序,如下所示:

./test test.txt

来源如下:

#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv)
{
    int temp =0;
    ifstream file;
    file.open(argv[1]);

    while(!file.eof())
    {
        temp=file.get();
            file.ignore(1,',');
        cout<<temp<<' ';
    }
    return 0;
}

出于某种原因,我的输出不是1 2 5 6but 49 50 53 54。是什么赋予了?

更新:

另外,我注意到还有另一种实现get()。如果我定义了char temp,那么我可以这样做file.get(temp),这也将节省我转换 ASCII 表示的时间。但是我喜欢使用while (file >> temp),所以我会继续使用。谢谢。

4

4 回答 4

1

temp is an int. So you see the encoded ascii values after casting the char to an int.

于 2013-02-24T01:05:58.627 回答
0

49 is the ascii code for digit 49-48 = 1.

get() gives you a character (character code).

by the way, eof() only becomes true after a failed read attempt, so the code you show,

while(!file.eof())
{
    temp=file.get();
        file.ignore(1,',');
    cout<<temp<<' ';
}

will possibly display one extraneous character at the end.

the conventional loop is

while( file >> temp )
{
     cout << temp << ' ';
}

where the expression file >> temp reads in one number and produces a reference to file, and where that file objected is converted to bool as if you had written

while( !(file >> temp).fail() )
于 2013-02-24T01:05:45.777 回答
0

作为记录,尽管这是第 n 个重复,以下是此代码在惯用 C++ 中的外观:

for (std::string line; std::getline(file, line); )
{
    std::istringstream iss(line);

    std::cout << "We read:";

    for (std::string n; std::getline(iss, line, ','); )
    {
        std::cout << " " << n;

        // now use e.g. std::stoi(n)
    }

    std::cout << "\n";
}

如果您不关心行或只有一行,则可以跳过外循环。

于 2013-02-24T01:15:36.293 回答
0

这不会像您认为的那样做:

while(!file.eof())

这在为什么循环条件内的 iostream::eof 被认为是错误的?,所以我不会在这个答案中介绍它。

尝试:

char c;
while (file >> c)
{
    // [...]
}

...反而。读入 achar而不是 anint也可以让您不必转换表示形式(ASCII 值 49 是1等等...)。

于 2013-02-24T01:12:17.237 回答