[cs13001] converting from integer to string and back

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Feb 27 13:42:25 EST 2013


CSI students,

Depending on how you code lab #7, you may need to convert from string
to integer and back. Traditional way of doing it in C++ is rather
clunky. However, the new C++11 standard has a number of handy type
conversion functions. For example

	   stoi  <-- accepts a string argument and returns an integer 
	   to_string <-- accepts numeric types and returns their
	   	     	 string representation

Microsoft Visual Studio C++ partially implements C++
standard. Function "to_string" is a bit awkward: before passing it an
integer argument, it needs to be cast to long long. Below is the
example usage of both functions.

Thanks,
-- 
Mikhail


-------------------
// demonstrates usage of string conversion functions
// requires C++11
// Mikhail Nesterenko
// 2/27/2013

#include <iostream>
#include <string>

using namespace std;

int main(){


    string s = "123";
    int i = stoi(s);
    cout << "integer variable contains: " << i << endl;
    i++;
    s = to_string(long long(i)); 
    cout << "string variable contains: " << s << endl;
}


More information about the cs13001 mailing list