2012-04-04 174 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