问题
I have a string xxxxxxxxxxxxxxxxxxx
I am reading the string into a structure of smaller strings, and using substr to parse it. I need to convert one of those string types to integer.
atoi is not working for me,. any ideas? it says cannot convert std::string to const char*
Thanks
#include<iostream>
#include<string>
using namespace std;
void main();
{
string s="453"
int y=atoi(S);
}
回答1:
std::atoi() requires const char * to pass in.
Change it to:
int y = atoi(s.c_str());
or use std::stoi() which you can pass a string directly:
int y = stoi(s);
You program has several other errors. Workable code could be something like:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s = "453";
int y = atoi(s.c_str());
// int y = stoi(s); // another method
}
回答2:
#include <sstream>
int toInt(std::string str)
{
int num;
std::stringstream ss(str);
ss >> num;
return num;
}
回答3:
In c++ the case matters, if you declare your string as s you need to use s not S when calling it, you are also missing a semicolon to mark the end of the instruction, on top of that, the atoi takes char * as parameter not a string, so you need to pass in an array of char or a pointer to a char array :
function signature: 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;
}
来源:https://stackoverflow.com/questions/23567924/convert-string-to-int-in-c