0

I am trying to get a element of string and cast it as a integer. What I am ultimately doing is in a for loop taking an element out of the string and convering that element to an int. This is in order to get the characters ascii value.

thanks

4
Contributors
3
Replies
5
Views
6 Years
Discussion Span
Last Post by jonsca
0

I believe what you are looking for is the Atoi function.

Here is a quick example

#include <iostream>
#include <string> // used for string support
#include <stdlib.h> // used for atoi() support
using namespace std;

int main()
{
 string theString = "12345"; // the string we are going to convert
 int i; // integer to store string value into
 i = atoi(theString.c_str()); // we use the c_str() to convert the function to a c-string which is the parameter that atoi takes
 cout << theString << " is now in the integer " << i << endl;
 return 0;
}
0

Another approach is to use stringstream class

#include <string>
#include <sstream>
#include <iostream>

int main()
{
   std::string s = "123";
   int x;
   std::stringstream str(s);
   str >> x;
   std::cout << x << '\n';
   std::cin.get();
}
0

This is in order to get the characters ascii value.

In a direct fashion:

std::string s = "123";
std::cout<<(int)s[0]<<std::endl; //outputs 49 (use your for loop to access all of the characters) the value of '1'

Edited by jonsca: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.