PDA

View Full Version : fgets() from command line




dvince2
Sep 23, 2008, 10:05 AM
Hey everyone
I've tried googling this, but I can't seem to find anything close to what I'm doing.
I have to read in a line that the user enters in the terminal... sort of like this:

Enter a Sentence
> This is a sentence entered by the user.

I'd like to use fgets() to accomplish this, but I'm not sure how to pass the console in as a parameter. Every example I can find is fgets(line, LINE_MAX, fp), where line is my char array, LINE_MAX is the max to read in, and fp is a pointer to a file. How can I point to the console?

Thanks for your help with this n00b question!



kainjow
Sep 23, 2008, 10:10 AM
gets (http://www.cplusplus.com/reference/clibrary/cstdio/gets.html) might be what you're looking for.

toddburch
Sep 23, 2008, 10:38 AM
Use the predefined variable stdin instead of fp.

lee1210
Sep 23, 2008, 10:54 AM
Use the predefined variable stdin instead of fp.

You need to include stdio.h for stdin and stdout to be available, but otherwise this is the right way to do it.

-Lee

kainjow
Sep 23, 2008, 11:00 AM
So fgets with stdin is preferred over gets? Just curious, but what's the reasoning?

Edit: nevermind. Found this (http://www.beej.us/guide/bgc/output/html/multipage/gets.html) which explains it.

Aranince
Sep 23, 2008, 11:03 AM
Yea? And why not use std::cin << mystring;

EDIT: Ah, nvm.

toddburch
Sep 23, 2008, 11:55 AM
So fgets with stdin is preferred over gets? Just curious, but what's the reasoning?

Edit: nevermind. Found this (http://www.beej.us/guide/bgc/output/html/multipage/gets.html) which explains it.

And another link on why gets() is bad: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1049157810&id=1043284351

lee1210
Sep 23, 2008, 01:23 PM
And another link on why gets() is bad: http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1049157810&id=1043284351

I obviously agree that fgets is the right answer here, and the link provided has good information, but:

Termination of another, unrelated program


This is not really a risk on most modern OSs. Most processes have their own protected memory space now, so one program going crazy should not affect the memory space of others. If a program attaches to a shared memory segment it could easily corrupt that, and that could cause issues for other processes, but in the general case you shouldn't be able to do worse than killing the particular program in which the problem exists. This isn't to downplay the risk, but I think understanding things like this can be important for beginners.

-Lee

toddburch
Sep 23, 2008, 01:45 PM
Yep, looks like a hold-over from DOS days.

dvince2
Sep 23, 2008, 02:16 PM
Thanks a lot everyone! It never occurred to me that i could use stdin like that lol.