Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Anonymous
Anonymous asked in Computers & InternetProgramming & Design · 1 decade ago

c++ questions, converting string to int?

how do i convert string characters to int characters?

lets just say i made

string x = 1234

then how do i read it as a number, or switch it?

im assuming int z = x does not work

cause i want to multiply the value, lets say times it by 2 to make it 2468

4 Answers

Relevance
  • Cubbi
    Lv 7
    1 decade ago
    Favorite Answer

    There are many options (as with everything in C++)

    1. Use the standard conversion function stoi() (requires recent C++ compiler, such as MSVC 2010 or gcc 4.4)

    #include <string>

    #include <iostream>

    int main()

    {

         std::string s = "1234";

         int i = stoi(s);

         std::cout << "integer is " << i << '\n';

    }

    2) use the C library conversion function atoi() (it has poor error handling in case conversion fails, though)

    #include <string>

    #include <iostream>

    #include <cstdlib>

    int main()

    {

         std::string s = "1234";

         int i = atoi(s.c_str());

         std::cout << "integer is " << i << '\n';

    }

    3) use operator>> from a string stream:

    #include <string>

    #include <iostream>

    #include <sstream>

    int main()

    {

         std::string s = "1234";

         std::istringstream is(s);

         int i;

         is >> i;

         std::cout << "integer is " << i << '\n';

    }

    4) use lexical_cast from the boost library (www.boost.org) which will automatically use one of the above three methods or whatever else is more efficient on your platform

    #include <string>

    #include <iostream>

    #include <boost/lexical_cast.hpp>

    int main()

    {

         std::string s = "1234";

         int i = boost::lexical_cast<int>(s);

         std::cout << "integer is " << i << '\n';

    }

  • ?
    Lv 4
    4 years ago

    C Parse Int

  • 1 decade ago

    U have to parse the String to int....

    use parseInt() function for that

    ie. int z=parseInt(x);

    if it doen't work try Integer.ParseInt()

    i just confused with VB and c++ at this time..

    or just refer books to parse string as int or google it.

  • puffor
    Lv 6
    1 decade ago

    include <sstream>

    #include <string>

    using namespace std;

    // string to int

    string some_string;

    istringstream buffer(some_string);

    int some_int;

    buffer >> some_int;

    // int to string

    int some_int;

    ostringstream buffer;

    buffer << some_int;

    string some_string = buffer.str();

Still have questions? Get your answers by asking now.