2014-05-09 3 views
-2

나는 작은 문자열의 구조에 문자열을 읽기, 그것을 구문 분석 SUBSTR을 사용하고 xxxxxxxxxxxxxxxxxxx변환 문자열은 C++

문자열을 가지고에서 int로. 이러한 문자열 유형 중 하나를 정수로 변환해야합니다.

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); 

프로그램에 몇 가지 다른 오류가 있습니다. 당신이 s로 문자열을 선언하는 경우, 당신은 s, 당신은 또한의 끝을 표시하는 세미콜론 누락하지 S를 호출 사용해야하는 경우 문제 C++로

#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

: 무언가 같이 실행 가능한 코드가 될 수있다

함수 서명 :int atoi (const char * str);

당신은 문자 배열에 문자의 배열이나 포인터를 전달 할 수 있도록 교육, 그 꼭대기에, atoi는 매개 변수없는 문자열로 char *합니다
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을 작성할 때 : '{': old-style 공식 목록?) – user3472947

+0

헤더를 포함해야합니다. atoi 함수가 속한 함수이며, 함수의 헤더를 포함시켜야합니다. 업데이트 된 코드를 살펴보십시오. –

1
#include <sstream> 

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