[Solved] Want to store “char values” in array (in C language)


Array of char data type is called Sting. You can take a string’s input using scanf() and gets(). But if you use scanf(), the string will be input by pressing Space-bar or Enter. But if you use gets(), input will be given only by pressing the Enter key.

Example 1:

char s[100];
scanf("%s", s);

Example 2:

char s[100];
gets(s);

Now, if you want to input every single character individually, you can do that also:

    char s[100], c;
    int n, i, j;
    scanf("%d", &n);
    getchar();
    for(i=0; i<n; i++) {
        scanf("%c", &s[i]);
    }

    s[i] = '\0';

Now look, I wrote a getchar() after scanf("%d", &n);, because when you press enter after inputting n, a new line character (‘\n’) is also taken as input in the character next to n. So you must do this in case like this.

One more thing, you can take input any string containing spaces using scanf() also. Just do this:

char s[100];
scanf("%[^\n]", s);

solved Want to store “char values” in array (in C language)