【发布时间】:2011-01-14 20:44:22
【问题描述】:
我是第一次学习 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”中包含的确切数据类型。因此,我需要指定它,因此我选择将数据读取为字符。
- 我将文件中的每个数字作为字符读取并将其转换为整数值并将其存储在“整数”中。
- 因为我在“theinteger”中有一个整数,所以我想将它作为一个字符打印出来,但是 char thechar = char(theinteger);没有按预期工作。
我做错了什么?
【问题讨论】:
-
那么,你的程序现在做什么呢?
-
不应该是
using std::cout;吗? -
感谢您注意到我的错误。我提出了错误的代码。将在几分钟内更新。
-
这是我们错过在 SO 上看到的第一个问题的类型。恭喜。
-
这完全偏离了轨道,所以我写它只是作为评论。如果您可以掌握 Accelerated C++,请查看它。它有一种完全不同的学习 C++ 的方法,从 STL 和高级构造开始,然后再深入细节。
标签: c++ char ascii new-operator int