#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    3
    Rep Power
    0

    C : read only certain sizes ints from keyboard


    I want to read from the user 5 lines of 5 number each..

    I write this

    int array[5][5];
    for(i=0;i<5;i++)
    {
    printf("line %d : ", i+1);
    for(j=0;j<5;j++)
    {
    scanf("%1d", &array[i][j]);
    }
    }
    How can I check if the user would give more than 5 numbers in each row? IF the user gives over than 5 numbers I will printf a message for example

    Thank you!
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Whether you type
    1 2 3 4 5
    or
    1
    2
    3
    4
    5


    makes no difference to scanf.
    Spaces and newlines are equivalent separators as far as it is concerned.

    If you want to make sure they type in "1 2 3 4 5" (and only that), then you need to read a line using fgets(), then parse the line (sscanf or strtol) to make sure what you expect is really there.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    3
    Rep Power
    0
    Thanks for reply!

    char r[5];

    fgets(r,sizeof(r), stdin);

    Something like that? It doesn't work..


    (User will type 12345, no 1 2 3 4 5)
  6. #4
  7. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,376
    Rep Power
    1871
    Try a much bigger char array for your string.
    "1 2 3 4 5"
    is 9 characters, then there will be a \n and a \0 at the end.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    3
    Rep Power
    0
    That's it!
    Thank you very much!

IMN logo majestic logo threadwatch logo seochat tools logo