Converting a string to an integer

This is a discussion on Converting a string to an integer within the C++ Programming forums, part of the General Programming Boards category; Can anyone help me convert a string into an integer? For example I have a string containing "12345" then send ...

  1. #1
    Unregistered
    Guest

    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
    Anti-Terrorist
    Join Date
    Aug 2001
    Location
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    Posts
    742
    Code:
    #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;
    	else
    		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
    Posts
    189
    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
    Unregistered
    Guest
    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, 09:43 AM
  4. Converting string to integer...
    By Ham in forum C++ Programming
    Replies: 6
    Last Post: 01-26-2003, 12:43 AM
  5. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21