Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   About atoi function and const chars... (http://www.programmingforums.org/showthread.php?t=11872)

Mcoy Nov 13th, 2006 9:09 PM

About atoi function and const chars...
 
:

string temp;
    char temp2[3];
    int num_of_values;
   
    getline (myfile,temp);
   
    for(int i(0); i < 3; i++)
    {
            temp2[i] = temp[i];
    }
   
    num_of_values = atoi(temp2);


The goal of the above code was to read a line from a file (with the getline function) and convert it from string type to integer type with atoi(). When supplying the atoi function with the string, the compiler gave me an error saying that atoi did not accept strings, only const char*s. So I had to use the for loop that you see in my code to change each letter from the string to a char array. -Seems very redundant to me considering a string is simply a character array, or am I mistaken?
What is a better/more efficient/intuitive way to read integers into my program from a file?

DaWei Nov 13th, 2006 9:53 PM

Your terminology is too fuzzy. An array of char, terminated by a '\0', is often referred to as a string, and atoi would accept that. The C++ string class is something else, but you can access its array of char with ElStringo.c_str (). Atoi isn't a great choice, since an error will return the same thing as the value, zero, so you can't tell the difference. There are other things like strtol, etc., that work better. You might also wish to investigate string streams.

Narue Nov 14th, 2006 8:16 AM

>since an error will return the same thing as the value, zero, so you can't tell the difference
Not to mention undefined behavior if the value can't be represented by an int. atoi is only about two steps above gets on my eew-o-meter.

DaWei Nov 14th, 2006 8:34 AM

A whole two? ewwwwwwwwwwwww.


All times are GMT -5. The time now is 1:31 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC