正确代碼:
#include <iostream>
#include <stdio.h>
#include <string.h>
//#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[]) {
string num;
while(cin >> num ){
if(strcmp(num.c_str(),"0")!=0){
int res=0,i=0;
while(num[i]!='\0'){
res+=num[i]-'0';
i++;
}
while(res>=10){
//itoa(res,&num[0],10);
sprintf(&num[0],"%d",res);
i=0; res=0;
while(num[i]!='\0'){
res+=num[i]-'0';
i++;
}
}
cout << res << endl;
}
else break;
}
return 0;
}
分析:
如此簡單的一道題我寫得卻很糾結,因為對int和char之間的轉換不熟悉。代碼寫得也比較亂,還有重複的一個while循環,應該可以簡化的。
還可以簡化 if(strcmp(num.c_str(),"0")!=0)
成為 while(cin >> num && strcmp(num.c_str(),"0")!=0)
itoa函數隻能在vc下使用,它不是一個标準的庫函數。不要用它了,使用<stdio.h>下的sprintf,功能相同也更好用。
c++ string類型在使用字元串函數時不同于char*,它需要把“變量名”換成“變量名.c_str()”。例如num換成num.c_str()
c++ string類型在使用springf時要把變量名換成&num[0]。
另外注意,把char型數字傳給int型的簡單方法 res+=num[i]-'0';