在我的程序中,我必须将输入字符存储在变量中,然后将它们添加到数组中。但有没有办法每次都使用相同的变量?
char str1,str2;
printf("insert character");
scanf("%c",&str1);
printf("%c",str1);
printf("insert character");
scanf("%c",&str2);
printf("%c",str2);
我想做这样的事情但是使用一个变量。我也可以使用scanf超过1次吗?似乎可执行文件在给出第二个字符之前停止。
答案 0 :(得分:0)
是的,您可以多次使用scanf()
。您的问题实际上不是因为scanf();
,而是您的输入,要为您的程序中的第一个scanf()
提供输入,我们自然会做的是输入(通过键盘)一个字符然后点击ENTER KEY,当您点击ENTER KEY时会产生一个'\n'
字符,该字符由您的第二个scanf()
读取,这就是为什么您的第二个scanf()
没有等待您的预期输入,我需要在您使用'\n'
时手动清除此%c
。(使用%d %f %s
时会自动删除'\n'
,这就是我们在使用时不会遇到此问题的原因)。
To solve problem you can use "%c" like this " %c" (note space before %c, this skips '\n' characters)
scanf(" %c",&str1);
printf("%c",str1);
//code to add them to array's
scanf(" %c",&str1);//Have Re-Used the same variable str1.
printf("%c",str1);