-1

I'd like to create and manipulate an array of caracters. I don't want to use strings. here is my code in C language :

int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++){
        printf("Character at %d : ",i);
        scanf("%c",&s[i]);
        printf("%c",s[i]);
    }
    return 0;
}

When I execute it, it seems that :

  • The compiler jumps from an element at i in the array to the element at i+2
  • Nothing is added in the array. the array stays empty

I'd like to understand what's wrong with the scanf("%c",&s[i]); that I think it is that instruction wich causes the problems in this code.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Simo
  • 155
  • 3
  • 12

2 Answers2

4

scanf() doesn't work as you expected. scanf() also considers the enter that you press as a character. If you are adamant about using scanf(), here are a couple of workaround for your current code.

Method 1

int main(int argc, char *argv[]) {
    char s[4];
    char enter;
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf("%c", &s[i]);
        scanf("%c", &enter);
        printf("%c \n", s[i]);
    }
    return 0;
}

Method 2

Use the same code, but enter all the four character at once.

int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf("%c", &s[i]);
    }
    for(i = 0; i < 4; i++) {
        printf("\n %c", s[i]);
    }
    return 0;
}

Output looks like:

Character at 0 : abcd
Character at 1 : Character at 2 : Character at 3 :
a
b
c
d

Method 3

As mentioned by Xing in comments, this looks better way to achieve it. But make sure you note the whitespace added before %c in scanf().

int main(int argc, char *argv[]) {
    char s[4];
    int i;
    for(i = 0; i < 4; i++) {
        printf("Character at %d : ",i);
        scanf(" %c", &s[i]); // Note the whitespace before %c
        printf("\n %c", s[i]);
    }
    return 0;
}
bharadhwaj
  • 2,059
  • 22
  • 35
1

It doesn't work as you expected because scanf() takes only one character but it will only do that until you pressed enter. So the enter character is still in the buffer and to be read by the next iteration of scanf().

See How to clear input buffer in C? for suggestions on how to change the code.

adrtam
  • 6,991
  • 2
  • 12
  • 27