473,835 Members | 1,838 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

I just don't get it, really, I don't getline(char*,s treamsize);

I am trying to get character string from the user, to do that I use
getline(char_ty pe*, 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.getlin e(cstr, CHAR_MAX); //<<==seg fault
TIA

Oct 5 '05 #1
2 3468
"jalkadir" <ja******@goson ic.ca> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com.. .
I am trying to get character string from the user, to do that I use
getline(char_ty pe*, 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.getlin e(cstr, CHAR_MAX); //<<==seg fault


It's not 'getline()' that you don't get, your misunderstandin g
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(st d::cin, cstr);

'std::getline() ' is declared by <string>. Note the two major differences
from 'istream::getli ne()': 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 misunderstandin g
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
Oct 5 '05 #2
the "cstr" variable you defined (confusing name btw.) is a pointer to a
character. However, there is no memory allocated for it to point to.

You have two options.

a) Define cstr as "char cstr[ CHAR_MAX ];"
b) Allocate memory for it "char* cstr = new char[ CHAR_MAX ];"

In case b), don't forget to free the memory later "delete [] cstr;"

Even better would be to use std::string.

Cheers,
Andre

Oct 5 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2887
by: tinks | last post by:
I am getting a linking error when I do something like this: ifstream dataFile; dataFile.open(dataFileName_, ios::in); while(dataFile) { dataFile.getline(buffer, MAX_DATA_FILE_LINE_LEN); // This line creates linking issue on solaris }
11
1636
by: pashmina g. | last post by:
Hi, I'm reading the book "The C programming Language". I'm trying to do an exercise asking to find the longest line. I'm reading the book in sequence hence I shouldn't know anything about pointer yet. As a string is declared with "char string", the length is already specified, how can I store an arbitrary long string? I've tried to do something like
1
3082
by: Luke Wu | last post by:
I have been using the getline function from K&R2 for simple character input. The prototype is int getline(char *s, int limit); /* returns 0 to signal EOF */ This function simply calls getchar() in a loop, which breaks if EOF or too much input occurs (and places necessary '\0'). I always made sure the buffer pointed to by s was large (corresponding
3
1338
by: gordy | last post by:
Newbie question, please by gentle. I'm trying to read in a text file containing the days of the week, one on each line. Each line should be pointed to by an array of pointers to char but I'm ending up with each pointer pointing to the same string. #include <stdio.h> #include <stdlib.h> #define DAYS 7
4
2066
by: sk | last post by:
I'm trying to write a little function that acts very similar to scanf, but I suck at pointers and returning chars. My code: char *getline(){ char *string; char c; int i=0; while((c=getchar())!='\n'){
33
25229
by: Chen shuSheng | last post by:
I have a code: --------------------------- #include <iostream.h> #include <stdlib.h> int main() { int max=15; char line; getline(line,max); system("PAUSE");
3
3651
by: shyam | last post by:
Hi All I want to know if there is any problem with using fstream.getLine(char*, int ) function. My problem is that when I read a file using it, the program aborts when it reads the terminating newline of a file. This happens if I set the exception bits using exceptions(fstream::badbit | fstream::failbit | fstream::eofbit ).
13
2312
by: theronnightstar | last post by:
I seem to be having a problem with getline(). I have tried to find it on google, but I'm not seeing the answer. The goal of this section of code is simply to read in a line from a file to a string according to the conditions of the do...while statement. /////code void populate( vector<string>& unplayed_anagrams, string& word, const
3
25221
by: JackC | last post by:
Hi, How do i use stringstreams getline function to extract lines from an existing string? Say i have: string strlist = "line1\r\nLine2\r\nLine3\r\n"; I want to extract each line out into a vector array of strings, but i cant get stringstream working :(
0
10520
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10560
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10233
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6963
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5636
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5804
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4433
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3993
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3088
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.