Search code examples
c++arraysstringintegeratoi

C++ String to Integer Issue Using atoi(str.c_str())


I am trying to represent a variable in the form of a string to a integer, I have done so using;

atoi(str.c_str()) 

The string is originally obtained from a text file and stored into a;

CharArrayPtr cmemblock;

Which is then represented as a string;

    string str;

    for(int i = 0; i < numberofvalues; i++)
    {   
        str = cmemblock[i];
        int number = atoi(str.c_str());
        cout << number;


    }

If I was to change the 'cout' to print str;

str = cmemblock[i];
int number = atoi(str.c_str());
cout << str;

The number show correctly as stored in the text file

However, I require the output to be an integer so that I could represent it in a loop to search for a value stored in a array. So this is where 'number' comes into play, which is the reason why I am asking for your help, when;

cout << number;

Whenever a new line is read it is represented as '0' how would I go about removing this? If your require my full code it is in several different .cpp files and to prevent anyone copying my work I can only email it you, im sure you have already guessed it is part of a University Assignment.

Using Member Adosi code I came up with this;

         std::string str;

    for(int i = 0; i < numberofvalues; i++)
    {   

        str = cmemblock[i];
        std::stol(str);
        int number = std::stoi(str);
        cout << number;


    }

I get an error R6010. Have I done this wrong?


Solution

  • std::stoi(str)

    Use this instead of atoi

    C++11 has this and a few other functions such as std::stol() for longs, std::stof() for floats, etc.

    http://en.cppreference.com/w/cpp/string/basic_string/stol