Thread: string of numbers into int?

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    45

    string of numbers into int?

    How would I turn a string with regular numbers in it into an int. I need to turn something like char tmp[3] into int x.

  2. #2
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    atoi()

  3. #3
    VA National Guard The Brain's Avatar
    Join Date
    May 2004
    Location
    Manassas, VA USA
    Posts
    903
    Here is the FAQ for string to int conversion. It is a very good FAQ.. because it helped me write this function that I used in my blackjack game:


    Code:
    //Converts the first character of a playing card from 'string' to 'int' so numeric comparisons can be made.
    //Example:  string '2 of Diamonds' will be converted to integer '2'
    //istringstream can only accept the &address of the character to be streamed to integer
    int card_value(string card)  
    {
    	int result = 0;
    	
    	char *card_ptr;
    	
    	card_ptr = &card[0];	//string class variables can be treated like arrays	
    
    	istringstream myStream(card_ptr); //create a 'myStream' object of class istringstream 
      
    	if (myStream >> result)	//String to Integer conversion (works only for numeric face values)
        					 
    		return result;		//return an integer value 2 thru 10
    
    	    
    	else
    	{
        
    		if (*card_ptr != 'A')
    
    			return 10;	//'J', 'Q', and 'K' will return a face value of 10
    
    		else
    
    			return 11; //'A' will return a value of 11
    
    	}
    
    
    }
    • "Problem Solving C++, The Object of Programming" -Walter Savitch
    • "Data Structures and Other Objects using C++" -Walter Savitch
    • "Assembly Language for Intel-Based Computers" -Kip Irvine
    • "Programming Windows, 5th edition" -Charles Petzold
    • "Visual C++ MFC Programming by Example" -John E. Swanke
    • "Network Programming Windows" -Jones/Ohlund
    • "Sams Teach Yourself Game Programming in 24 Hours" -Michael Morrison
    • "Mathmatics for 3D Game Programming & Computer Graphics" -Eric Lengyel

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 08:19 AM
  2. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  3. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  4. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM