嗨,这是我在这个网站上的第一篇文章,我刚开始学习C编程。我试图寻找关于我的具体问题的其他帖子,但其他答案的复杂性让我有点不知所措。 (所以如果多余的话,我道歉)
我正在尝试编写一个带有4个输入数字的代码,然后将它们打印回给你,然后询问你是否想要使用y / n选项再次执行此操作。我需要一些帮助让计算机读取用户y / n输入,然后基于此继续/中断循环。以下是我到目前为止所得到的一些错误,谢谢。
#include <stdio.h>
int main()
{
int x[5];
char choice;
choice = 'y'; //Assigned choice to y//
while (choice == 'y')
{
printf("Please input up to four numbers seperated for example, 1 2 3 4 : ");
scanf_s("%d %d %d %d", &x[0], &x[1], &x[2], &x[3]);
printf("Your entries in reverse order are %d %d %d %d\n", x[3], x[2], x[1], x[0]); //This is working//
printf("Would you like to enter another set of numbers? <y/n>:");
scanf_s(" %c", choice); //Want this line to get an input y/n and if y, repeat the loop and if n, end the program//
}
printf("Goodbye\n");
system("Pause");
return 0 ;
}
答案 0 :(得分:2)
您需要将来电更改为scanf_s
,以便第二次输入以下内容:
scanf_s(" %c", &choice, 1);
请注意,1表示缓冲区大小。
来自MSDN
In the case of characters, a single character may be read as follows:
char c;
scanf_s("%c", &c, 1);
答案 1 :(得分:1)
应该是
scanf_s("%c", &choice, 1);
Scanf需要指向变量的指针。否则scanf将无法为&#34; choice&#34;提供新值。 这是一个流行的错误。
修改强> 如果搜索有关scanf_s的更多信息,则可以基于标准库中的scanf。 Scanf_s在功能上是scanf的精确对应物。 唯一的区别是scanf_s是安全的,因为它有额外的参数来确定变量的大小。
答案 2 :(得分:0)
首先学会缩进代码,这提高了很多可读性。改变
scanf_s(" %c", choice);
到
scanf(" %c", &choice);
将删除代码中的所有错误。
`