Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert std::string to integer

Tags:

c++

string

int

atoi

I'm trying to convert a std::string stored in a std::vector to an integer and pass it to a function as a parameter.

This is a simplified version of my code:

vector <string> record;
functiontest(atoi(record[i].c_str));

My error is as follows:

error: argument of type ‘const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const’ does not match ‘const char*’

How can I do this?

like image 998
Daniel Del Core Avatar asked Sep 27 '12 19:09

Daniel Del Core


People also ask

How do I convert a string to an integer in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.

How do I cast a Std string to int?

To convert from string representation to integer value, we can use std::stringstream. if the value converted is out of range for integer data type, it returns INT_MIN or INT_MAX. Also if the string value can't be represented as an valid int data type, then 0 is returned.

What is stoi () in C++?

In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.

Where is stoi defined C++?

The stoi function was introduced in C++11 and is defined in the header <string> . It throws std::invalid_argument or std::out_of_range exception on a bad input or integer overflow, respectively.


3 Answers

With C++11:

int value = std::stoi(record[i]);
like image 172
Pete Becker Avatar answered Oct 21 '22 15:10

Pete Becker


record[i].c_str

is not the same as

record[i].c_str()

You can actually get this from the error message: the function expects a const char*, but you're providing an argument of type const char* (std::basic_string<char, std::char_traits<char>, std::allocator<char> >::)()const which is a pointer to a member function of the class std::basic_string<char, std::char_traits<char>, std::allocator<char> > that returns a const char* and takes no arguments.

like image 35
Luchian Grigore Avatar answered Oct 21 '22 13:10

Luchian Grigore


Use stringstream from standard library. It's cleaner and it's rather C++ than C.

int i3;
std::stringstream(record[i]) >> i3; 
like image 11
Indy9000 Avatar answered Oct 21 '22 13:10

Indy9000