2014-03-26 101 views
0

我寫,我會給出一個字符串,如程序:C++在一個漫長的字符串的字符串轉換爲整數

5,6,10

和我做了一個程序,它數字5 6 10(忽略逗號)並將它們放入矢量中。 與我的程序唯一的問題是,如果我這樣做

5,6,F

它會變成使得f爲0。而我想,如果它認爲該計劃只是報告錯誤除0之外的任何東西0 1 2 3 4 5 6 7 8 9,

我該如何修復我的程序來做到這一點?這裏是我的代碼:

#include <cstdlib> 
#include <iostream> 
#include <string> 
#include <vector> 
using namespace std; 


int main() 
{ 
    string str, temp; 

    cout << "enter string: \n"; 
    getline (cin, str); 
    vector<int> vec; 
    int num; 

    for (int j=0; j < str.size(); j++) 
{ 
    int num2= str.size()-1; 

    if (isdigit(str[j])) 
    { 
     temp+= str[j]; 
     num = atoi(temp.c_str()); 
     if (num2 ==j) //if program is at end of string and it's still a number 
      vec.push_back(num); //push back value 
    } 
    else if (str[j] == ',') 
    { 
     num = atoi(temp.c_str()); 
     temp.clear(); 
     vec.push_back(num); 

    } 
    else 
    { 
     cout << "error\n"; 
     temp.clear(); 
    } 

} 
    for (int k=0; k < vec.size(); k++) 
     cout << vec[k] <<endl; 
} 

回答

0

這不是安全使用atoi,使用strtol代替。

atoi的文檔:

如果str不指向一個有效的C-串,或如果轉換後的值 會出由一個int值表示的範圍內的,它會導致 未定義的行爲。

例子:

// ... 

char *end; 
long int res = strtol(str, &end, 10); 
if (str == eptr) { 
    throw std::invalid_argument("invalid strtol argument"); 
} 
if (errno == ERANGE) { 
    throw std::out_of_range("strtol argument out of range"); 
} 

更新:您的代碼應該是這個樣子:

char *iter = str.c_str(); // your str 
char *end; 
while (*iter) { 
    int res = strtol(iter, &end, 10); 

    // not a number, skip it and continue with the next one 
    if (iter == end) { 
     iter++; 
     cout << "error: " << *iter << endl; 
     continue; 
    } 

    // handle the out-of-range error 
    if (errno == ERANGE) { 
     cout << "overflow: " << string(iter, end) << endl; 
    } else { 
     // number is valid 
     vec.push_back(res); 
    } 

    // continue iterating, skip char at (*end) since it's not an integer 
    iter = end + 1; 
} 

警告:前面的代碼編譯時不也測試

+0

我有我的程序執行strtol時遇到麻煩。我通讀了cpp對它的定義,它仍然有點不妥。你可以給我一個例子或者我的程序或者一個開始? – Mdjon26