Reading a string as input with scanf

I am new to C and am trying to read a character and string (max-length 25 sentence) from the user.

Not sure what I am doing wrong in the following lines of code, this gives me a "Segment Failure" error.

#include <stdio.h>

int main(){
    char * str[25];
    char car;

    printf("Enter a character: ");
    car = getchar();

    printf("Enter a sentence: ");
    scanf("%[^\n]s", &str);

    printf("\nThe sentence is %s, and the character is %s\n", str, car);

    return 0;
}

Thanks!

+4
source share
3 answers

str- an array of 25 pointers to char, not an array char. So change his ad to

char str[25];

And you cannot use scanfto read sentences - it stops reading in the first space, so use fgetsto read sentences.

printf %c , %s. , stdin '\n', .

#include <stdio.h>    
void flush();
int main()
{
    char str[25], car;

    printf("Enter a character\n");
    car = getchar();

    flush();

    printf("Enter a sentence\n");
    fgets(str, 25, stdin);

    printf("\nThe sentence is %s, and the character is %c\n", str, car);

    return 0;
}
void flush()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;
}
+5

:

  • char * str[25];
    

    char str[25];
    

    25 char s, 25 char.

  • char car;
    

    int car;
    

    getchar() int, char.

  • scanf("%[^\n]s", &str);
    

    scanf( "%24[^\n]", str);
    

    scanf

    • , .
    • 24 (+1 Nul-terminator '\0') \n str.
  • printf("\nThe sentence is %s, and the character is %s\n", str, car);
    

    printf("\nThe sentence is %s, and the character is %c\n", str, car);
    

    char %c, %s.

+4

//

#include <stdio.h>

int main(){

    char car,str[25];

    printf("Enter a character: ");
    car = getchar();

    printf("Enter a sentence: ");
    scanf("%s", str);

    printf("\nThe sentence is %s, and the character is %c\n", str, car);

    return 0;
}
0

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


All Articles