Entering user input into a char array (C programming)

I need to read input from the console and put it in an array of characters. I wrote the following code, but I get the following error: "Segmentation Error"

#include <stdio.h>
#include <stdlib.h>

int main() {

    char c;
    int count;
    char arr[50];

    c = getchar();
    count = 0;
    while(c != EOF){
        arr[count] = c;
        ++count;
    }


    return (EXIT_SUCCESS);

}
+3
source share
3 answers
#include <stdio.h>
#include <stdlib.h>
int main() {
    char c;                /* 1. */
    int count;
    char arr[50];
    c = getchar();         /* 2. */
    count = 0;
    while (c != EOF) {     /* 3. and 6. and ... */
        arr[count] = c;    /* 4. */
        ++count;           /* 5. */
    }
    return (EXIT_SUCCESS); /* 7. */
}
  • cmust be int. getchar () returns an int to distinguish between a valid character and EOF
  • Read symbol
  • Compare this symbol with EOF: if different transition to 7
  • Put this character in an array arr, elementcount
  • Prepare a β€œdifferent” character in the next element of the array
  • Check the character read in 1. for EOF

You need to read different characters in a loop each time. (3., 4., 5.)

, , . (4).

:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int c;                 /* int */
    int count;
    char arr[50];
    c = getchar();
    count = 0;
    while ((count < 50) && (c != EOF)) {    /* don't go over the array size! */
        arr[count] = c;
        ++count;
        c = getchar();     /* get *another* character */
    }
    return (EXIT_SUCCESS);
}

, , - , ? , :

/* while (...) { ... } */
/* arr now has `count` characters, starting at arr[0] and ending at arr[count-1] */
/* let print them ... */
/* we need a variable to know when we're at the end of the array. */
/* I'll reuse `c` now */
for (c=0; c<count; c++) {
    putchar(c);
}
putchar('\n'); /* make sure there a newline at the end */
return EXIT_SUCCESS; /* return does not need () */

: printf(). , arr : , () 0 (NUL). NUL .

NUL arr, 50 , 49 ( NUL) NUL .

arr[count] = 0;
+8
#include <stdio.h>
#include <stdlib.h>

int main() {

    int c;
    int count;
    int arr[50];

    c = getchar();
    count = 0;
    while( c != EOF && count < 50 ){
        arr[count++] = c;
        c = getchar();
    }


    return (EXIT_SUCCESS);

}

&& count < 50 while. arr.

+5

I have a little suggestion.
Instead of c = getchar();twice in the program,
modify the while loop as follows:

while( (c = getchar()) != EOF && count < 50 ){
        arr[count++] = c;
}
+3
source

Source: https://habr.com/ru/post/1717380/


All Articles