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

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;
}

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();
}

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'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.