[英]Read a string as an input using scanf
I am new to C language and I am trying read a character and a string (a sentence; max-length 25) from a user.我是 C 语言的新手,我正在尝试从用户那里读取一个字符和一个字符串(一个句子;最大长度 25)。
Not sure what I am doing wrong in the following lines of code, its giving me an error "Segment Fault".不确定我在以下代码行中做错了什么,它给了我一个错误“段错误”。
#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!谢谢!
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 to char
.因为您想要一个包含 25 个
char
的数组,而不是一个包含 25 个指向char
指针的数组。
Change改变
char car;
to到
int car;
as getchar()
returns an int
, not a char
.因为
getchar()
返回一个int
,而不是一个char
。
Change改变
scanf("%[^\\n]s", &str);
to到
scanf( "%24[^\\n]", str);
which tells scanf
to这告诉
scanf
'\\0'
) or until a \\n
and store it in str
.'\\0'
为 +1)或直到一个\\n
并将其存储在str
。 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
.因为
char
的正确格式说明符是%c
,而不是%s
。
str
is an array of 25 pointers to char
, not an array of char
. str
是一个包含 25 个指向char
指针的数组,而不是一个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.并且您不能使用
scanf
来阅读句子——它会在第一个空格处停止阅读,因此请改用fgets
来阅读句子。
And in your last printf
, you need the %c
specifier to print characters, not %s
.在您的最后一个
printf
,您需要%c
说明符来打印字符,而不是%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.您还需要刷新标准输入,因为
stdin
剩余一个'\\n'
,因此您需要将这些字符扔掉。
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)
;
}
// This is minimal change to your code to work // 这是对您的代码进行的最小更改以使其正常工作
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.