2013-10-11 66 views
3

您好我是新來的C++和試圖做一個任務,我們要從一個txt文件中的C++字符串爲int不使用的atoi()或Stoi旅館()

surname,initial,number1,number2 

格式讀取大量數據在有人建議以字符串的形式讀取2個值之前,我要求幫助,然後使用stoi()或atoi()將其轉換爲int。這很好,除了我需要使用這個參數「-std = C++ 11」進行編譯或者它會返回一個錯誤。這在我自己的計算機上不會出現問題,它將處理「-std = C++ 11」,但不幸的是對於我來說,我必須提供我的程序的機器沒有這個選項。

如果有另一種方法可以將字符串轉換爲不使用stoi或atoi的int?

這是我的代碼到目前爲止。

while (getline(inputFile, line)) 
{ 
    stringstream linestream(line); 

    getline(linestream, Surname, ','); 
    getline(linestream, Initial, ','); 
    getline(linestream, strnum1, ','); 
    getline(linestream, strnum2, ','); 
    number1 = stoi(strnum1); 
    number2 = stoi(strnum2); 

    dosomethingwith(Surname, Initial, number1, number2); 
} 
+0

首先,你不應該在atoi中需要'-std = C++ 11'。但我會避免'atoi',因爲它不允許任何錯誤檢查。更好的解決方案是「strtoi」。 –

+0

當你想要的是'istringstream'時,使用'stringstream'這個狂熱是什麼? (我一直都在看,而且我不明白爲什麼有人會這樣做。) –

+0

另外,對於這種格式,而不是'istringstream',我會使用類似'boost :: split'的東西仍然存在轉換爲「int」的問題)。 –

回答

0

您已經在使用stringstream,它爲您提供了這樣的「功能」。

void func() 
{ 
    std::string strnum1("1"); 
    std::string strnum2("2"); 
    int number1; 
    int number2; 
    std::stringstream convert; 

    convert << strnum1; 
    convert >> number1; 

    convert.str(""); // clear the stringstream 
    convert.clear(); // clear the state flags for another conversion 

    convert << strnum2; 
    convert >> number2; 
} 
+0

爲什麼簡單,當你可以變得複雜?你不需要(不一定需要)雙向'stringstream'。只需使用'istringstream',用正確的字符串初始化即可。 –

4

我想你可以寫你自己的stoi函數。 這裏是我的代碼,我測試過了,非常簡單。

long stoi(const char *s) 
{ 
    long i; 
    i = 0; 
    while(*s >= '0' && *s <= '9') 
    { 
     i = i * 10 + (*s - '0'); 
     s++; 
    } 
    return i; 
} 
+2

首先,他沒有'char const *',而是'std :: string'。其次,這些功能需要更多的錯誤檢查,如果他們是有用的。 –