2012-04-04 126 views
1

第一年有學習問題將ascii轉換爲int。將ascii substr轉換爲int

問題是這樣的一段代碼

無符號短iminutes =((分鐘[3] -48)×10)+(分鐘[4] -48);

當我在家裏的代碼塊上運行它時,它返回一個不正確的值,當我再次運行它時,我得到了一個不正確的值。

當我在大學的Borland上運行它時,屏幕剛剛起來並消失,因此我無法在此處使用系統時鐘。

現在是復活節了,即使我在大學時,我也不能因爲他們不是我的老師而煩惱。

#include <iostream.h> 
#include <conio.h> 
#include <string> 
//#include <time.h> 
//#include <ctype.h> 


using namespace std; 

int main() { 

bool q = false; 


do { 

// convert hours to minutes ... then total all the minutes 
// multiply total minutes by $25.00/hr 
// format (hh:mm:ss) 


string theTime; 

cout << "\t\tPlease enter time " << endl; 
cout <<"\t\t"; 
cin >> theTime; 
cout << "\t\t"<< theTime << "\n\n"; 

string hours = theTime.substr (0, 2); 
cout <<"\t\t"<< hours << endl; 
unsigned short ihours = (((hours[0]-48)*10 + (hours[1] -48))*60); 
cout << "\t\t"<< ihours << endl; 

string minutes = theTime.substr (3, 2); 
cout <<"\t\t"<< minutes << endl; 
unsigned short iminutes = ((minutes[3]-48)*10) + (minutes[4]-48); 
cout << "\t\t" << iminutes << endl; 

cout << "\n\n\t\tTotal Minutes " <<(ihours + iminutes); 
cout << "\n\n\t\tTotal Value " <<(ihours + iminutes)*(25.00/60) << "\n\n"; 

} 

while (!q); 

cout << "\t\tPress any key to continue ..."; 
getch(); 
return 0; 
} 

回答

0

的問題是,即使你從原始字符串獲得在位置3和4的人物,新的字符串就是兩個字符(即只有指數在0和1)。

+1

另一個問題是,他減去'48',而不是'」 0''。 (還有,他沒有驗證他有數字開頭。) – 2012-04-04 09:46:47

0
istringstream iss(theTime.substr(0, 2)); 
iss >> ihour; 
1

您將分鐘設置爲theTime的子字符串。所以分鐘有2個字符。第一個從幾分鐘內的位置0開始。

所以這

unsigned short iminutes = ((minutes[3]-48)*10) + (minutes[4]-48); 

是錯誤的,因爲它訪問字符3和在不存在分4,因爲分鐘長只有兩個字符。它只有字符位置0和1

應該是這個

unsigned short iminutes = ((minutes[0]-48)*10) + (minutes[1]-48); 

,或者您可以使用此:

unsigned short iminutes = ((theTime[3]-48)*10) + (theTime[4]-48); 
+0

太棒了...謝謝你和所有其他答案 – Phill 2012-04-04 10:40:46