converting string to int!

This is a discussion on converting string to int! within the C++ Programming forums, part of the General Programming Boards category; I got only one error that I do not know how to get it fixed! Code: #include <iostream> using namespace ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    58

    converting string to int!

    I got only one error that I do not know how to get it fixed!


    Code:
    #include <iostream>
    using namespace std;
    
    int main(){
    string num;
    int i = 0;
    	
    	
    	cout << "Insert a number between 10-99"<<endl;
    	cin >> num;
    	
       i = atoi(num);
    	
    	if ((i > 9) && (i < 100)){
    		cout << "The Inverse number of the input is    " << num[1]<< num[0] << endl;
    	}
    	else{
    		cout << "ERROR: You must select a number between 10-99" << endl;
    	}
    	
    	return 0;
    }

  2. #2
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    You're missing a bunch of header files.
    I'd recommend using a stringstream to convert between strings & numbers though.

    Code:
    std::stringstream ss;
    ss << "666";
    int num;
    ss >> num;
    Of course you'd also want to do some checking to see if the conversion failed...

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,182
    atoi() takes a c-string as input

    Code:
       i = atoi(num.c_str());

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by cyberfish View Post
    atoi() takes a c-string as input

    Code:
       i = atoi(num.c_str());
    And atoi() is not a particularly "user friendly" function, as there's nearly no way to determing if the input was rubbish or valid data. If you must use non-stringstream functions, use strtol().

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Registered User
    Join Date
    Jan 2008
    Posts
    225
    Try converting string to float. You should also validate like for example the string cannot have more than 1 decimal point. The string should be a valid number etc.And yeah most importantly... don't use atof() function!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Debug Error Really Quick Question
    By GCNDoug in forum C Programming
    Replies: 1
    Last Post: 04-23-2007, 12:05 PM
  3. Quack! It doesn't work! >.<
    By *Michelle* in forum C++ Programming
    Replies: 8
    Last Post: 03-01-2003, 11:26 PM
  4. 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