输入
输入中将有几行以包含单个 *
的行结尾。这最后一行
不应该被处理。每行将包含 Hajj
或 Umrah
。
输出
对于输入的每一行,在单独的行中输出 Hajj-e-Akbar
或 Hajj-e-Asghar
报价单。有关确切格式,请参阅示例。
这是我解决这个问题的代码。
#include <stdio.h>
int main()
{
char str[100];
int i = 1;
while (scanf("%s", &str))
{
if (str[0] == '*')
break;
else if (str[0] == 'H')
printf("Case %d: Hajj-e-Akbar\n", i);
else
printf("Case %d: Hajj-e-Asghar\n", i);
i++;
}
}
对于输入
Hajj
Umrah
*
当我一次给出这个输入时,程序通过打印提供预期的输出
Hajj
Case 1: Hajj-e-Akbar
Umrah
Case 2: Hajj-e-Asghar
*
但是在得到*
作为输入后,程序正在等待Enter
。按 Enter
后,程序终止。但是我希望我的程序在输入 *
时终止,而不是通过按 Enter
来终止。请在这里帮助我。但这不是我的问题。我的问题是针对相同的输入-
Hajj
Umrah
*
当我通过 scanf("%s\n", &str)
获取输入时。该程序不会在第一次输入 Hajj
后打印输出 Case 1: Hajj-e-Akbar
但它会在接受第二个输入 后打印第一次输入的输出副朝
。然后程序等待输入 *
的 Enter
。
输出是这样的
Hajj
Umrah
Case 1: Hajj-e-Akbar
*
然后我按 Enter
,它为第二个输入 Umrah
打印输出 Case 2: Hajj-e-Asghar
然后等待另一个输入。这是按 Enter
后的输出。
Hajj
Umrah
Case 1: Hajj-e-Akbar
*
Case 2: Hajj-e-Asghar
我不明白 \n
对 scanf
有什么影响。
谢谢。
如果我不能正确解释我的问题,我很抱歉。我是编程新手。
最佳答案
scanf
读取格式化输入,所以当你使用 %s\n”, &str
该字符串将被消耗并存储在 str
中换行符也是如此,当您按下回车键时,它将出现在缓冲区中,字符串将被存储,换行符将被丢弃。
注意正确的用法是“%s\n”, str
, str
已经是你不应该使用的指针 &
.
当您使用 “%s”, &str
时换行符将留在缓冲区中,并将在下一个循环中使用,因此 str
将存储在第一次迭代中,"\n"
将存储在 str
中在下一次迭代中,只有在第三次迭代中才会再次要求您输入。
如以下评论所述,根据 scanf
的定义完成:
...any single whitespace character in the format string consumes all available consecutive whitespace characters from the input (determined as if by calling isspace in a loop). Note that there is no difference between "\n", " ", "\t\t", or other whitespace in the format string.
我还建议您限制 scanf
期望的字符串的大小避免容器溢出,类似%99s
对于像您这样的 100 个字符的容器,还要检查 scanf
返回,在这种情况下,它必须是= 1
对于每个周期。
做你想做的事,我收集的是从stdin
中获得一个角色在不按回车键的情况下,您将需要一个特定于 SO 的方法,这里是 Windows 使用 <conio.h>
的一个小示例图书馆,和getch()
:
#include <stdio.h>
#include <conio.h>
int main()
{
int i = 1, c;
while (1)
{
if ((c = getch()) == '*')
return 0;
else if (c == 'H')
printf("Case %d: Hajj-e-Akbar\n", i);
else
printf("Case %d: Hajj-e-Asghar\n", i);
i++;
}
}
对于 Linux,一种选择是同时使用 getch()来自 <ncurses.h>
图书馆,你might need to install .
PS:别担心,您的问题构建得很好,特别是在站点中仅排在第二位。
关于c - scanf ("%s", &str) 和 scanf ("%s\n", &str) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61248228/