Joshua Vaughan
Joshua Vaughan

Reputation: 347

How to convert a c string to an integer using std::stoi in C++

Let's say I have a sample of C-strings as follows:

"-fib 12"
"-fib 12"
"-e 2"
"-pi 4"

I would like to use the std::stoi function to get the last number in the C-strings into an integer variable. I have never before used the stoi function and it is rather confusing trying to get this to work. Thanks!

Upvotes: 0

Views: 1730

Answers (2)

Naumann
Naumann

Reputation: 417

Using std::string, you can also do something like...

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "15";
    std::string str2 = "3.14159";
    std::string str3 = "714 and words after";
    std::string str4 = "anything before shall not work, 2";
    int myint1 = std::stoi(str1);
    int myint2 = std::stoi(str2);
    int myint3 = std::stoi(str3);

    // int myint4 = std::stoi(str4); // uncomment to see error: 'std::invalid_argument'
    std::cout << myint1 << '\n'
              << myint2 << '\n'
              << myint3 << '\n';
    //  << myint4 << '\n';
}

output

15
 3 //discarded the decimal portion since it is int
714 // discarded characters after the digit

Upvotes: 0

R Sahu
R Sahu

Reputation: 206667

You'll have to first get past the non-numeric data before the space character to be able to use std::stoi.

char* s = "-fib 12";

// Skip until you get to the space character.
char* cp = s;
while ( *cp != ' ' && *cp != '\0') cp++;

// Defensive programming. Make sure your string is not
// malformed. Then, call std::stoi.
if ( *cp == ' ' )
{
   int num = std::stoi(cp);
}

Upvotes: 1

Related Questions