Thread: Converting a string to an integer

  1. #1

    Question Converting a string to an integer

    Can anyone help me convert a string into an integer? For example I have a string containing "12345" then send that string to a function and have it returned as the number 12345. Thanks for the help.

  2. #2
    Join Date
    Aug 2001
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    #include <iostream>
    using namespace std;
    int Convert(char *);
    int main()
    	char *s_str = "1234";
    	int i_num = Convert(s_str);
    	cout << i_num * 2;
    int Convert(char *st)
    	int i_num;
    	int status = sscanf(st,"%d",&i_num);
    	if(status == 1) return i_num;
    		return 1; //in C++ throw an exception
    This uses sscanf to do it. It extracts the characters from the string and turns them into whatever you specify. If the specified type does not match what is in the string, than sscanf will return an error value. You should look up sscanf under you compilers help.

    There is probably a more mature C++ way to do this but I'm rather new to C++ myself. I just wanted to give an example using sscanf.
    I compile code with:
    Visual Studio.NET beta2

  3. #3
    Ethereal Raccoon Procyon's Avatar
    Join Date
    Aug 2001
    There's a C function called atoi() that converts C-strings (char *) to integers. Is that good enough, or do you want to convert actual C++ strings directly?

  4. #4
    Thanks ever so much. This board is great.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  3. load gif into program
    By willc0de4food in forum Windows Programming
    Replies: 14
    Last Post: 01-11-2006, 10:43 AM
  4. Converting string to integer...
    By Ham in forum C++ Programming
    Replies: 6
    Last Post: 01-26-2003, 01:43 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM