【问题标题】:First %s scanf value get ignore but second %s can store the value第一个 %s scanf 值被忽略,但第二个 %s 可以存储该值
【发布时间】:2020-12-16 12:22:16
【问题描述】:
int main()
{
    char i;
    char s;
    printf("Enter first char : ");
    scanf("%s", &i);
    printf("Enter second char : ");
    scanf("%s", &s);
    printf("%c", i);
    printf("%c", s);
}

输出结果只打印第二个scanf值,而第一个scanf值不打印出来。

int main()
{
    char i;
    char s;
    printf("Enter first char : ");
    scanf("%c", &i);
    printf("Enter second char : ");
    scanf(" %c", &s);
    printf("%c", i);
    printf("%c", s);
}

当更改为使用 %c 时,两个 scanf 值都可以打印出来。

为什么 %s 只存储最后一个输入而第一个被忽略?

【问题讨论】:

  • 您不能在带有标量 char 变量的 scanf 中使用 %s%s 写入一个字符串,包括一个终止空字符,因此使用标量char 的地址将导致内存损坏。要么更改%s,要么改用char 数组。
  • 所以 %s 应该是 char s[10] 类型的吧?
  • 类似的东西。请记住,没有长度检查,因此 char s[10] 将适用于最长 9 个字符的字符串(加上一个用于空字符)。
  • 您应该永远使用原始的%s,原因与您永远不应该使用gets 完全相同。您需要char s[2]; scanf("%1s", s)char s; scanf("%c", s),或者做正确的事并完全停止使用scanf。只需执行int s; s = getchar();,然后在while 循环中丢弃空格。

标签: c


【解决方案1】:

%s 是扫描字符串:

scanf(" %s",&string);

或者

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

%c 只扫描一个字符:

scanf(" %c",&caracter);

在您的第一个代码中,如果您想读取两个字符串并打印它们:使用此代码

#include <stdio.h>

int main()
{
    char i[150];
    char s[150];
    printf("Enter first char : ");
    scanf("%s[^\n]",i);//scan the first string
    printf("Enter second char : ");
    scanf("%s[^\n]",s);//scan the second string
    printf("%s", i);
    printf("\n");
    printf("%s", s);
    printf("\n");
    printf("%c",i[1]);//if you want to print the second caracter in the string i
    printf("\n");
    printf("%c",s[0]);//if you want to print the first caracter in the string s
}

【讨论】:

  • 感谢您的解释。我知道 %s 用于长度与您给出的示例一样的字符串。只是有这个问题,因为我的老师用错误的方法教我这样
  • 你有”%s[^\n]”,它扫描一个以空格分隔的字符串,然后查找一个开方括号、一个插入符号、一个任意且可能为空的空格序列和一个右方括号,但它可能找不到那些文字。您可能打算使用”%[^\n]”,这是一个寻找一系列非换行符的扫描集。请注意,在扫描集之前和之后都没有s
  • @JonathanLeffler:扫描一个字符串,我可以使用它:scanf("%[^\n]s",string);或 scanf("%s[^\n]",string)
  • 两者都不正确 — 扫描集转换说明符不使用 s。在一定程度上,两者都会起作用。第一个查找一系列非换行符,后跟一个字母 a,它找不到,但它无法报告该失败。第二个将读取输入中的第一个单词,然后(通常)无法找到以下文字字符。它也没有办法在这里报告失败。如果您在这些之后进行了其他转换,您将能够更容易地发现失败。如果没有办法报告问题,尾随文字可能无法匹配。
  • 为那些固执地认为“非”应该是“无”的血腥咒语者道歉。
猜你喜欢
  • 2013-10-16
  • 2021-10-06
  • 2017-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
相关资源
最近更新 更多