嗨,有人能指出我這個代碼有什麼問題嗎?C++整理負輸出
#include <stdio.h>
int convstrg(char* str) {
int output = 0;
char* p = str;
for (int i=0;str[i]!='\0';i++) {
char c = *p++;
if (c < '0' || c > '9')
continue;
output *= 10;
output += c - '0';
}
return output;
}
int main(){
char x[] = "1xx23";
printf("%d\n", convstrg(x));
return 0;
}
當輸出爲字符串整數時,代碼應該返回一個整數。但似乎我越來越怪異號碼,如0
這是一些測試情況下,它的一些工作,一些沒有
"123" -> 123
"23xyz" -> 23
"" -> 0
"abc" -> 0
"-1" -> -1
感謝
編輯
好了,現在我有點所有的情況下預計負字符串..
@icabod問題是負數爲「-1」我得到1的回報 – d3bug3r
你必須處理負值沒有邏輯 - 你需要補充一點。但是,既然這是C++,那麼爲什麼當有更好的替代品不需要編碼時,你甚至會重新發明這種輪子(並使用C-stye編碼)? –
@novavent:是的,只是看到它不會爲負面工作,所以刪除了我的評論:) – icabod