2014-05-09 237 views
-2

我有一個字符串xxxxxxxxxxxxxxxxxxx將字符串轉換爲int在C++

我讀的字符串轉換成較小的字符串的結構,並使用SUBSTR解析它。 我需要將其中一個字符串類型轉換爲整數。

atoi不適合我,。有任何想法嗎?它說:cannot convert std::string to const char*

感謝

#include<iostream> 

#include<string> 

using namespace std; 

void main(); 

{ 
    string s="453" 

     int y=atoi(S); 
} 
+0

'atoi'是不是如果你需要驗證,它成功地轉換爲使用一個很不錯的功能,更好的東西來使用是'strtol': [Documentation](http://www.cplusplus.com/reference/cstdlib/strtol/) – Rogue

回答

2

std::atoi()需要const char *在通過

將其更改爲:

int y = atoi(s.c_str()); 

或使用std::stoi(),你可以直接傳遞一個string

int y = stoi(s); 

您的程序有其他幾個錯誤。可行的代碼可能是這樣的:

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

int main() 
{ 
    string s = "453"; 
    int y = atoi(s.c_str()); 
    // int y = stoi(s); // another method 
} 
+0

非常感謝您的幫助 – user3472947

1

在C++的情況下的問題,如果你申報你的字符串作爲s你需要使用s不調用它時S,你還缺少一個分號標記的結束指令,最重要的是,該atoi需要char *作爲參數不是字符串,所以需要在字符數組或指針的字符數組傳遞:

函數簽名:int atoi (const char * str);

string s="453"; // missing ; 

int y=atoi(s.c_str()); // need to use s not S 

UPDATE:

#include<cstdlib> 
#include<iostream> 
#include<string> 

using namespace std; 

void main() // get rid of semicolomn here 
{ 
    string s="453"; // missing ; 
    int y=atoi(s.c_str()); // need to use s not S 
    cout << "y =\n"; 
    cout << y; 
    char e;  // this and the below line is just to hold the program and avoid the window/program to close until you press one key. 
    cin >> e; 
} 
+0

當我編寫代碼時這個erroe apear錯誤C2447:'{':missing function header(old-style正式名單?) – user3472947

+0

你需要包含你的頭文件atoi函數屬於,並且您需要確保包含您的任何函數的標題。看看更新的代碼。 –

1
#include <sstream> 

int toInt(std::string str) 
{ 
    int num; 
    std::stringstream ss(str); 
    ss >> num; 
    return num; 
}