From: Greg Comeau on
In article <3qn797Ffnii1U1(a)individual.net>,
Jochen Rundholz <jochen_r(a)gmx.de> wrote:
>Karl Heinz Buchegger wrote:
>> Jochen Rundholz wrote:
>>> I want to ask for several values and enter should go for the default. I
>>> tried the following:
>>>
>>> int a = 0;
>>> cout << "Enter a value, hit enter for default [0]: ";
>>> cin >> a;
>>>
>>> It doesn't work... any idea what I can do?
>>
>> Yep. Don't read as int, read the user input as string.
>> If the user enters an empty string, you know that you have
>> to apply the default value. If the user did not enter an empty
>> string, convert that string to a number.
>
>Okay, I'll do it that way. This way I won't have a backspace problem either.
>Google told me two different versions to convert an integer to int:
>
>int a;
>string s="5";
>a = atoi(s) // doesnt work

Right, it won't.

>a = atoi(s.c_str()); //this works
>
>Is the first call just something old and outdated?

Nope, never worked with a std::string argument.
At least not as far as Standard C or Standard C++ is concerned.

>Why doesn't it work?

Because it is not specified to take std::strings.
Its origin is in C. With C++ there are other choices.
Furthermore, even if C atoi should be used cautiously, if at all.
See http://www.comeaucomputing.com/techtalk/#atoi

>I thought the s.c_str() converts a string to a char pointer

It does, that why the second one works, or can work.

>and furthermore
>I've read in some documentation that atoi() needs a string as an argument.
>I am puzzeled...

This is a terminology problem. Formally, C does not string
types, although we like to talk about "...." and things that
char *'s point to (char[]s) a `strings', especially as the
library section of Standard C refers to them in that way.
So a C programmer might refer to a string meaning a `C string',
being one of those things just mentioned.

However, a C++ programmer might also mention a string and
will probably be referrring to a `std::string' (say "standard string",
though this is not officialese either).

So, when you read on some google link that atoi take a string,
it was referring to a so-called C string.
--
Greg Comeau / Celebrating 20 years of Comeauity!
Comeau C/C++ ONLINE ==> http://www.comeaucomputing.com/tryitout
World Class Compilers: Breathtaking C++, Amazing C99, Fabulous C90.
Comeau C/C++ with Dinkumware's Libraries... Have you tried it?