0

How can i convert a string of number (and i mean string not char ,because the atoi function works for char ,and didn't work for string for me) to an integer . I tried this but it didn't work :

int main(){
int P,W;
string ST1 , ST2;
getline(cin,ST1,' ');
getline(cin,ST2);
P = std::atoi(ST1);
W = std::atoi(ST1);
return 0 ;
}
0

1 Answer 1

1

You can call any function taking a const char * with a string using .c_str():

P = std::atoi(ST1.c_str());
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but why do that when there's std::stoi?
@us2012: This technique is generally useful for calling any function that takes const char *, not merely for converting strings to integer. Also, std::stoi is C++11 (and later) only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.