2013-10-31 68 views
1

我想將字符串轉換爲整數。我記得有一位老師說,像你這樣的東西必須從中減去48,但我不確定,當我這樣做時,我得到17作爲A的值,這就是如果我是正確的64. 這裏是我的代碼。任何更好的方式將不勝感激。
將str轉換爲int的簡單方法? C++

#include <cstdlib> 
#include <iostream> 
#include <conio.h> 
using namespace std; 
int main() 
{ 
    string str; 
    getline(cin,str); 
    cout << str[0] - 48; 
    getch(); 
} 
+1

這隻適用於數字,你應該減去''0'。 – chris

+0

可能的重複[如何解析一個字符串到一個int在C + +?](http://stackoverflow.com/questions/194465/how-to-parse-a-string-to-an-int-in-c) – villintehaspam

+0

這個問題是類似的,並且大多數答案將適用:http://stackoverflow.com/questions/1012571/stdstring-to-float-or-double –

回答

1

僅使用C++設施簡單且類型安全的解決方案是以下方法:

#include <iostream> 
#include <sstream> 

int fromString(const std::string& s) 
{ 
    std::stringstream stream; 
    stream << s; 

    int value = 0; 
    stream >> value; 

    if(stream.fail()) // if the conversion fails, the failbit will be set 
    {     // this is a recoverable error, because the stream 
        // is not in an unusable state at this point 
    // handle faulty conversion somehow 
    // - print a message 
    // - throw an exception 
    // - etc ... 
    } 

    return value; 
} 

int main (int argc, char ** argv) 
{ 
    std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think) 
    std::cout << std::stoi("123") << std::endl; // C++ 11 

    return 0; 
} 

注意:在fromString()你應該檢查,看看是否該字符串的所有字符實際上形成一個有效的積分值。例如,GH1234或其他東西不會,並且調用operator>>後值將保持爲0。

編輯:只記得,檢查轉換是否成功的簡單方法是檢查流的failbit。我相應地更新了答案。

0

還有就是atoi函數的字符串轉換爲int,但我猜你要做到這一點沒有庫函數。

我可以給你最好的線索就是看看ASCII表,記住:

int c = '6'; 
printf("%d", c); 

將打印的「6」的ASCII值。

1

A不是數字,那麼如何將它轉換爲int?你的代碼已經有效。例如,輸入5,您會看到5作爲輸出。當然,因爲您只是在打印該值,所以沒有任何區別。但是,你可能會存儲在int變量,而不是:

int num = str[0] - 48; 

順便說一句,通常'0'是用來代替48(48是0 ASCII碼)。所以你可以寫str[0] - '0'

+0

而使用「0」而不是「48」的原因是有些系統不使用ASCII。沒有理由在這裏建立無用的。 –

0

有一個在cstdlib,做它最簡單地稱爲atoi功能: http://www.cplusplus.com/reference/cstdlib/atoi/

int number = atoi(str.c_str()); // .c_str() is used because atoi is a C function and needs a C string 

的方式將這些功能的工作是沿着這些線路:

int sum = 0; 
foreach(character; string) { 
    sum *= 10; // since we're going left to right, if you do this step by step, you'll see we read the ten's place first... 
    if(character < '0' || character > '9') 
     return 0; // invalid character, signal error somehow 

    sum += character - '0'; // individual character to string, works because the ascii vales for 0-9 are consecutive 
} 

如果你給的是 「23」 ,它變爲0 * 10 = 0。0 +'2' - '0'= 2.

下一次循環迭代:2 * 10 = 20 20 +'3' - '0'= 23

完成!