fgets() from command line

Discussion in 'Mac Programming' started by dvince2, Sep 23, 2008.

  1. macrumors 6502

    dvince2

    #1
    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!
     
  2. Moderator emeritus

    kainjow

    #2
    gets might be what you're looking for.
     
  3. macrumors 6502a

    #3
    Use the predefined variable stdin instead of fp.
     
  4. macrumors 68040

    lee1210

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

    -Lee
     
  5. Moderator emeritus

    kainjow

    #5
    So fgets with stdin is preferred over gets? Just curious, but what's the reasoning?

    Edit: nevermind. Found this which explains it.
     
  6. macrumors 65816

    #6
    Yea? And why not use std::cin << mystring;

    EDIT: Ah, nvm.
     
  7. macrumors 6502a

    #7
  8. macrumors 68040

    lee1210

    #8
    I obviously agree that fgets is the right answer here, and the link provided has good information, but:
    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
     
  9. macrumors 6502a

    #9
    Yep, looks like a hold-over from DOS days.
     
  10. macrumors 6502

    dvince2

    #10
    Thanks a lot everyone! It never occurred to me that i could use stdin like that lol.
     

Share This Page