Read a string as an input using scanf
You have to make four changes:
Change
char * str[25];
to
char str[25];
as you want an array of 25
char
s, not an array of 25 pointers tochar
.Change
char car;
to
int car;
as
getchar()
returns anint
, not achar
.Change
scanf("%[^\n]s", &str);
to
scanf( "%24[^\n]", str);
which tells
scanf
to- Ignore all whitespace characters, if any.
- Scan a maximum of 24 characters (+1 for the Nul-terminator
'\0'
) or until a\n
and store it instr
.
Change
printf("\nThe sentence is %s, and the character is %s\n", str, car);
to
printf("\nThe sentence is %s, and the character is %c\n", str, car);
as the correct format specifier for a
char
is%c
, not%s
.
str
is an array of 25 pointers to char
, not an array of char
. So change its declaration to
char str[25];
And you cannot use scanf
to read sentences--it stops reading at the first whitespace, so use fgets
to read the sentence instead.
And in your last printf
, you need the %c
specifier to print characters, not %s
.
You also need to flush the standard input, because there is a '\n'
remaining in stdin
, so you need to throw those characters out.
The revised program is now
#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)
;
}