我正在第一次學習C++。我沒有以前的編程背景。C++混亂。從文本文件讀取整數。轉換爲ASCII
在書中我看到了這個例子。
#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形式讀取數據。
- 我讀取文件中的每個數字作爲char並將其轉換爲整數值並將其存儲在「整數」中。
- 因爲我在「theinteger」中有一個整數,所以我想把它打印出來作爲一個字符,但char thechar = char(theinteger);不按預期工作。
我在做什麼不正確?
那麼,你的程序現在做了什麼? – Sam 2010-02-09 15:19:24
不應該是'使用std :: cout;'? – Manuel 2010-02-09 15:25:58
感謝您注意我的錯誤。我提出了錯誤的代碼。將在幾分鐘內更新它。 – newbie 2010-02-09 15:27:07