Help with scanf and arrays - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Help with scanf and arrays

KotikKotik Posts: 7Member
I am currently learning C and have come across an issue I cannot find an answer anywhere. Basically I want an input of 10 digits (all in one singular input) and scan each number into an array.

Let me clarify a little more with the code:
[code]#include
#define N 10

int main(void)
{
int i, a[10];
printf("Please enter the 10 digits (sith spaces in between) (Y Y M M D D X X X X) : ");
for (i=0; i<N; i++)
{
scanf("%1d", a[i]);
}
printf("%d", a[3]);
return 0;
}[/code]

Basically I want the user to input 10 digits and then have those numbers scanned into an array. I don't want to do it the easy way of having the user type 1 digit at a time followed by hitting the enter key every time.

However this code of mine gives a "segmentation fault." So I assume I'm doing something wrong.

Any help appreciated!
Kotik

Comments

  • raxxaraxxa Posts: 3Member
    Hi

    I'm just re-learning C, and as far as I know scanf is a buffered input, which means that it reads input until ENTER is pressed.

    I would solve this problem by reading into a char array instead. This would mean that the input is entered without spaces:

    [code]
    #include
    #define N 10

    int main(void)
    {
    int i;
    char a[10];
    printf("Please enter the 10 digits (sith spaces in between) (Y Y M M D D X X X X) : ");

    scanf("%s", &a);

    printf("%c", a[3]);
    return 0;
    }
    [/code]

    Hope this helps.

    Cheers!

    /John
  • raxxaraxxa Posts: 3Member
    [-----------------------------------]
Sign In or Register to comment.