473,958 Members | 52,209 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 3481
"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
2903
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
1642
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
3092
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
1343
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
2077
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
25261
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
3654
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
2321
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
25233
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
10264
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11707
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
11325
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...
0
7529
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
6305
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
6447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
5061
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
4643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3656
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.