jalkadir said:
I am trying to get character string from the user, to do that I use
getline(char_type*, streamsize), but I get a segmentation fault??!!
Can anyone give me a hand, what am I doing wrong?
--snip
char* cstr;
std::cout << "House/Appartment # ";
std::cin.getline(cstr, CHAR_MAX); //<<==seg fault
It's not 'getline()' that you don't get, your misunderstanding
is much more fundamental. 'getline()'s first argument is a
pointer to char, but that pointer needs to point to some
(sufficient number of contiguous) characters, i.e. an array
of characters. You have only provided a pointer, but failed
to cause it to point anywhere. It's the fact that 'getline()'
will dereference this pointer that causes the problem in your
code. Dereferencing an invalid or NULL pointer gives 'undefined
behavior', where *anything* could happen. Consider yourself
fortunate that this time the problem is visible, as a 'segmentation
fault'. THe language makes no requirement at all what the behavior
would be. Equally possible would be a failure with no visible
indications.
Perhaps part of your trouble is that you've fallen into a very
common novice error: not distinguishing between a pointer an
an array. A pointer is not an array. An array is not a pointer.
A type 'char*' object is *not* a string (although it can be made
to point to one (A 'c-style string, that is)).
Also, your (attempted) use of 'C-style' strings, with all the attendant
potential for errors, is unnecessary. Use the std::string class for
strings.
That's what it's for.
std::string cstr; // automatically is a well-defined object with a
// valid value (in this case, an empty string)
std::cout << "House/Apartment # ";
std::getline(std::cin, cstr);
'std::getline()' is declared by <string>. Note the two major differences
from 'istream::getline()': It's a nonmember function, and it stores
characters in a std::string object rather than a character array.
A std::string object manages its own memory, so you can't run into
a problem like you did with an uninitialized 'char*'.
A final note about your code: You also seem to be misunderstanding
the meaning and purpose of the 'CHAR_MAX' macro. It's defined as
returning a value which is the largest possible value for a single
character object. It has nothing to do with a count of characters
or stream operations.
Which C++ book(s) are you reading?
-Mike