looping to get user input

This is a discussion on looping to get user input within the C Programming forums, part of the General Programming Boards category; Hi all, Second newbie question of the day! I'm building a program that gets input from the user. I am ...

  1. #1
    Registered User
    Join Date
    Oct 2009
    Posts
    21

    looping to get user input

    Hi all,

    Second newbie question of the day! I'm building a program that gets input from the user. I am using scanf to get a line and then do some processing and this is working fine. The problem comes when I try to loop through this until the user enters 'quit'. It works fine the first time round but then just goes into an infinite loop. The code is below:

    Code:
    while (1) {
    
    char expr[100] = {0};
    
    printf("Input Expression:");
    scanf("%[^\n]", expr);
    
    if (strcmp(expr, "quit") == 0) { return 0; }
    
    // do stuff here
    
    printf("\n");
    
    }
    This has been simplified by removing some extra code that processes the input however I don't think this is where the problem lies. I think it's something to do with the scanf but am unsure what. Any pointers greatly appreciated!

    Cheers,
    James

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,652
    Aren't you missing a type specifier in your scanf?

  3. #3
    Registered User
    Join Date
    Oct 2009
    Posts
    21
    I could well be... basically I want to read in one line of data, I thought that was how to read in one line? How would you suggest doing it?

  4. #4
    Registered User
    Join Date
    Mar 2009
    Posts
    399
    The way you've used scanf is inherently unsafe. See the FAQ for better methods: Cprogramming.com FAQ > Get a line of text from the user/keyboard (C)

  5. #5
    Registered User
    Join Date
    Oct 2009
    Posts
    21
    That did the trick, thanks alot! I've been tearing my hair out over this for ages!

    James

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. can someone help me with these errors please code included
    By geekrockergal in forum C Programming
    Replies: 7
    Last Post: 02-10-2009, 01:20 PM
  2. SSH Hacker Activity!! AAHHH!!
    By Kleid-0 in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 03-06-2005, 02:53 PM
  3. Nested Structures - User Input
    By shazg2000 in forum C Programming
    Replies: 2
    Last Post: 01-09-2005, 09:53 AM
  4. looping and input
    By Kinasz in forum C Programming
    Replies: 2
    Last Post: 03-17-2003, 06:12 AM
  5. comparing user input
    By lambs4 in forum C Programming
    Replies: 5
    Last Post: 12-15-2002, 09:28 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21