3 Replies - 261 Views - Last Post: 06 May 2013 - 05:36 AM Rate Topic: -----

#1 jaipurchanchal  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 01-May 13

input using gets()

Posted 06 May 2013 - 02:42 AM

i am having a problem getting input from gets()
before gets i have to input a number using scanf. After giving the value of scanf when i press enter it reads it as a string in gets i dont want that i want to give the value of string in the next line
i tried getchar after scanf but it didnt solve my problem.
small part of my code
scanf("%d",&n);
gets(str);


is there a way that gets read only my string and not newline characters

Is This A Good Question/Topic? 0
  • +

Replies To: input using gets()

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6074
  • View blog
  • Posts: 23,540
  • Joined: 23-August 08

Re: input using gets()

Posted 06 May 2013 - 02:45 AM

DON'T USE gets() AT ALL!!

Use fgets() to read in a line and sscanf() to parse it.
Was This Post Helpful? 1
  • +
  • -

#3 peace_fixation  Icon User is offline

  • D.I.C Head

Reputation: 45
  • View blog
  • Posts: 198
  • Joined: 01-November 11

Re: input using gets()

Posted 06 May 2013 - 04:58 AM

scanf() doesn't consume the '\n' character, so the next function that reads input from stdin will. I never use scanf() for anything.

My practise is to read a line like this:

// read LINE_LENGTH characters from stdin, store in line
fgets(line, LINE_LENGTH, stdin);
// consume the rest of the input until a '\n' character is found
while(getc() != '\n') {}
// now parse line, maybe using sscanf, or your own custom string-to-whatever function
sscanf(line, "%s", myvar);



I'm a bit rusty actually, it's been a while! o.O
Was This Post Helpful? 1
  • +
  • -

#4 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: input using gets()

Posted 06 May 2013 - 05:36 AM

fgets will consume and add the '\n' char on to the end of the string in the input buffer IF the buffer has room

I think you meant to code something like this:

char* fixedFgets( char* s, size_t bufSize, FILE* fin )
{
    if( fgets( s, bufSize, fin ) )
    {
        char *p = strchr( s, '\n' ), c ;
        if( p ) *p = 0; /* strip off '\n' at end ... IF it exists */
        else while( (c = fgetc( fin )) != '\n'  &&  c != EOF ) ; /* flush... */
        return s;
    }
    /* else */
    return NULL;
}



This post has been edited by David W: 06 May 2013 - 05:41 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1