Thread: How can I get a fixed length string without side-effect?

  1. #1
    Registered User
    Join Date
    Nov 2009
    Posts
    5

    Question How can I get a fixed length string without side-effect?

    Hi there,

    Here is what I've tried:
    Code:
    #include<stdio.h>
    
    int main(){
      char str[10];
      int a;
      fgets(str, 10, stdin);
      scanf("%d", &a);
      printf("str is %s and the int is %d.\n", str, a);
    }
    the result is:
    $ ./test
    abc 123 37482 <-- input
    str is abc 123 3 and the int is 7482. <-- output
    The str is what I want but the int is not.
    What I want is like this:
    $ ./test
    abc 123 37482 <-- input
    123 <-- another input for the int
    str is abc 123 3 and the int is 123. <-- output
    How can I achieve this?

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Since fgets() is truncating the string because you have limited it, the remaining chars are still in the input buffer. Suck them out until you have sucked out the newline. Then, issue the scanf().
    Mainframe assembler programmer by trade. C coder when I can.

  3. #3
    Registered User
    Join Date
    Nov 2009
    Posts
    5
    Oh, I see. Thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  2. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. Linking error
    By DockyD in forum C++ Programming
    Replies: 10
    Last Post: 01-20-2003, 05:27 AM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM