【问题标题】:Incorrect char from file文件中的字符不正确
【发布时间】:2013-02-24 00:58:34
【问题描述】:

我有以下 .txt 文件:

test.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 6,而是49 50 53 54。什么给了?

更新:

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

【问题讨论】:

    标签: c++ text-files iostream fstream cout


    【解决方案1】:

    temp 是一个整数。因此,在将 char 转换为 int 后,您会看到编码后的 ascii 值。

    【讨论】:

      【解决方案2】:

      49 是数字 49-48 = 1 的 ASCII 码。

      get() 给你一个字符(字符代码)。

      顺便说一句,eof() 仅在读取尝试失败后变为为真,所以你显示的代码,

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

      最后可能会显示一个无关字符。

      常规循环是

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

      表达式file &gt;&gt; temp 读入一个数字并产生对file 的引用,而被反对的file 被转换为bool,就像你写的一样

      while( !(file >> temp).fail() )
      

      【讨论】:

        【解决方案3】:

        这并不像你认为的那样:

        while(!file.eof())
        

        Why is iostream::eof inside a loop condition considered wrong? 对此进行了介绍,因此我不会在此答案中介绍。

        试试:

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

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

        【讨论】:

          【解决方案4】:

          为了记录,尽管这是第 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";
          }
          

          如果你不关心行或者只有一行,你可以跳过外层循环。

          【讨论】:

            猜你喜欢
            • 2016-05-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-03-01
            • 2020-08-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多