Simple C question
|
Original Message
|
Name: igor12
Date: April 18, 2005 at 11:19:02 Pacific
Subject: Simple C questionOS: LinuxCPU/Ram: 2Ghz/512 |
Comment: I have a question about inputting strings. char* tester; tester = malloc( sizeof(char) * 100); scanf("%s", tester); printf("\nThe String: %s\n", tester); exit(1); If, for example, I input "test string", the string returns "test" and does not record anything after the whitespace. So I have 2 questions: 1) How do I record the string without using array notation. 2) Is there a way to dynamically allocate memory to the string so that I can input a string of any size? Thanks, Igor
Report Offensive Message For Removal
|
|
Response Number 1
|
Name: dtech10
Date: April 18, 2005 at 14:05:57 Pacific
Subject: Simple C question |
Reply: (edit)Hi My C's a bit rusty. scanf() function will quit on a blank spaces. This will get your string correctly. scanf("%s %s",tester) but gets(tester) would be much better with strings.
Report Offensive Follow Up For Removal
|
|
Response Number 2
|
Name: Wolfbone
Date: April 18, 2005 at 14:59:01 Pacific
Subject: Simple C question |
Reply: (edit)Why not RTFM? As pointed out, you are getting what you asked for with scanf: the first word alone. info libc 'I/O on streams' 'Formatted Input' info libc 'I/O on streams' 'Line Input' see getline()
Report Offensive Follow Up For Removal
|
|
Response Number 3
|
Name: sen (by santanusen_82)
Date: April 19, 2005 at 23:18:25 Pacific
Subject: Simple C question |
Reply: (edit)Hey, wanna scan a whole line including blanks and tabs? Use the following scanf("%[^\n]", tester);
For dynamically allocating space for a string use linked lists. I think you are familiar with data structures, right?
Best of luck. Santanu Sen National Institute of Technology Durgapur India
Report Offensive Follow Up For Removal
|
|
Response Number 4
|
Name: Wolfbone
Date: April 20, 2005 at 00:34:29 Pacific
Subject: Simple C question |
Reply: (edit)How big is the line? How big is tester?... You could make that work properly using the GNU 'a' flag for dynamic string input to scanf but getline is the right way to get a whole line of input anyway, not scanf. Linked list? What's wrong with realloc - I don't think Igor is writing a Lisp implementation ;-)
Report Offensive Follow Up For Removal
|
|
Response Number 5
|
Name: RAMPKORV
Date: May 10, 2005 at 01:09:27 Pacific
Subject: Simple C question |
Reply: (edit)It was suggested earlier to use gets() instead of scanf(). In my opinion, gets() is the most useless crap in C, because it lets the user type more than 100 character and cause a segfault in your program. Instead, use fgets(), and have it read from stdin.
Report Offensive Follow Up For Removal
|
Use following form to reply to current message: