C ++困惑。从文本文件中读取整数。转换为ASCII

时间:2010-02-09 15:17:01

标签: c++ char ascii new-operator int

我是第一次学习C ++。我以前没有编程背景。

在书中,我看到了这个例子。

#include <iostream>

using::cout;
using::endl;

int main()
{
    int x = 5;
    char y = char(x);

    cout << x << endl;
    cout << y << endl;

    return 0;
}

该示例有意义:打印整数及其ASCII表示。

现在,我创建了一个包含这些值的文本文件。

48
49
50
51
55
56
75

我正在编写一个程序来读取这个文本文件 - “theFile.txt” - 并希望将这些数字转换为ASCII值。

这是我写的代码。

#include <iostream>
#include <fstream>

using std::cout;
using std::endl;
using std::ifstream;

int main()
{
    ifstream thestream;
    thestream.open("theFile.txt");

    char thecharacter;  

    while (thestream.get(thecharacter))
    {
        int theinteger = int(thecharacter);
        char thechar = char(theinteger);
        cout << theinteger << "\t" << thechar << endl;
    }


    system ("PAUSE");
    return 0;
}

这是我对第二个节目的理解。

  • 编译器不知道“theFile.txt”中包含的确切数据类型。因此,我需要指定它,因此我选择将数据作为字符读取。
  • 我将文件中的每个数字读取为char并将其转换为整数值并将其存储在“theinteger”中。
  • 因为我在“theinteger”中有一个整数,我想把它作为一个字符打印出来但是char char = char(theinteger);不按预期工作。

我做错了什么?

2 个答案:

答案 0 :(得分:6)

您正在通过char读取char,但您确实(我认为)想要将每个数字序列读取为整数。将你的循环改为:

int theinteger; 
while (thestream >> theinteger )
{
    char thechar = char(theinteger);
    cout << thechar << endl;
}

+1对于格式非常好的&amp;第一个问题,BTW!

答案 1 :(得分:2)

您正在从文件中一次读取一个字符。因此,如果您的文件包含:

2424

您将首先从文件中读取字符“2”,将其转换为int,然后返回到char,它将在cout上打印“2”。下一轮将打印“4”,依此类推。

如果您想将数字读作全数,则需要执行以下操作:

int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;