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

new*_*bie 11 c++ int ascii char new-operator

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

我在书中看到了这个例子.

#include <iostream>

using::cout;
using::endl;

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

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这个例子很有意义:打印一个整数及其ASCII表示.

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

48
49
50
51
55
56
75
Run Code Online (Sandbox Code Playgroud)

我正在编写一个程序来读取这个文本文件 - "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;
}
Run Code Online (Sandbox Code Playgroud)

这是我对所显示的第二个程序的理解.

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

我做错了什么?

小智 6

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

int theinteger; 
while (thestream >> theinteger )
{
    char thechar = char(theinteger);
    cout << thechar << endl;
}
Run Code Online (Sandbox Code Playgroud)

+1对于一个非常好的格式和表达的第一个问题,BTW!


Håv*_*d S 2

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

2424
Run Code Online (Sandbox Code Playgroud)

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

如果您想将数字读取为完整数字,您需要执行以下操作:

int theinteger;
thestream >> theinteger;
cout << char(theinteger) << endl;
Run Code Online (Sandbox Code Playgroud)