Thread: How can terminate input when input specifed char?

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    77

    How can terminate input when input specifed char?

    I wanna do this
    Code:
    char chr[10];
    while (scanf("%s", chr) != 'x') {
           ...........
    }
    Means the prog is terminated in the following input data.
    Code:
    0001
    1003
    0206
    0034
    1111
    1003
    x      <------ When I input 'x', the program stop
    the while code doesn't work...... How can I implement this action?

  2. #2
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
    while(fgets(chr,10,stdin) != NULL)
    {
       if(chr[0] == 'x')
          break;
       //do something
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  3. #3
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Code:
    char chr[10];
    while (scanf("%s", chr) != 'x') {
           ...........
    }
    More this will not work. in fact. Scanf returns no of arguments read from the used. Avoid using scanf. You could do something like this if your want

    Code:
        while((ch=getchar() != 'x') && ch != 'X');
        
        printf("You are out\n");
    ssharish2005
    Last edited by ssharish2005; 12-10-2006 at 05:02 AM.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You never need to typecast chars to ints.


    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User ssharish2005's Avatar
    Join Date
    Sep 2005
    Location
    Cambridge, UK
    Posts
    1,732
    Quote Originally Posted by quzah
    You never need to typecast chars to ints.


    Quzah.
    Quzah true, but for some reason when i wrote that code, it wasn't getting the ASCII value of X. That the reason when type casted it on purpose.

    Any code updated

    ssharish2005

  6. #6
    Registered User
    Join Date
    Apr 2005
    Posts
    77
    For example, how to read the data? [Problem: http://acm.hnu.cn:8080/online/?actio...=show&id=10658
    I don't know to read the data......

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. About aes
    By gumit in forum C Programming
    Replies: 13
    Last Post: 10-24-2006, 03:42 PM
  2. code condensing
    By bcianfrocca in forum C++ Programming
    Replies: 4
    Last Post: 09-07-2005, 09:22 AM
  3. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 01:18 AM
  4. getline problem
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 10-06-2001, 09:28 AM