因此,谷歌快速搜索fflush(stdin)清除输入缓冲区会发现许多网站警告不要使用它.然而,这正是我的CS教授教授课程的原因.
使用有多糟糕fflush(stdin)?即使我的教授正在使用它并且似乎完美无缺地工作,我是否真的应该放弃使用它?
有一个很好的方法循环一个字符串sscanf吗?
假设我有一个如下所示的字符串:
char line[] = "100 185 400 11 1000";
Run Code Online (Sandbox Code Playgroud)
我想打印这笔款项.我真正想写的是:
int n, sum = 0;
while (1 == sscanf(line, " %d", &n)) {
sum += n;
line += <number of bytes consumed by sscanf>
}
Run Code Online (Sandbox Code Playgroud)
但是没有干净的方法来获取这些信息sscanf.如果它返回消耗的字节数,那将是有用的.在这样的情况下,人们可以使用strtok,但能够写出类似于你可以做的事情的东西是很好的stdin:
int n, sum = 0;
while (1 == scanf(" %d", &n)) {
sum += n;
// stdin is transparently advanced by scanf call
}
Run Code Online (Sandbox Code Playgroud)
有一个我忘记的简单解决方案吗?
我正在尝试开发一个简单的基于文本的刽子手游戏,并且主游戏循环以提示输入每个字母的猜测开始,然后继续检查字母是否在单词中并且如果它生命关闭不是.但是,当我运行游戏时,每次提示两次,程序不会等待用户的输入.它也会夺去生命(如果它是正确的输入就会有一个生命,如果没有,则为两个生命),所以无论它采取的是什么都与之前的输入不同.这是我的游戏循环,简化了一下:
while (!finished)
{
printf("Guess the word '%s'\n",covered);
scanf("%c", ¤tGuess);
i=0;
while (i<=wordLength)
{
if (i == wordLength)
{
--numLives;
printf("Number of lives: %i\n", numLives);
break;
} else if (currentGuess == secretWord[i]) {
covered[i] = secretWord[i];
secretWord[i] = '*';
break;
}
++i;
}
j=0;
while (j<=wordLength)
{
if (j == (wordLength)) {
finished = 1;
printf("Congratulations! You guessed the word!\n");
break;
} else {
if (covered[j] == '-') {
break;
}
}
++j;
if (numLives == 0) {
finished = …Run Code Online (Sandbox Code Playgroud) 每当我在fgets之前执行scanf时,fgets指令就会被跳过.我已经在C++中解决了这个问题,我记得我必须有一些可以清除stdin缓冲区或类似内容的指令.我想C有一个等价物.它是什么?
谢谢.
在第5行中,我读取一个整数,isint如果读取整数则为1,如果不是整数则为0.如果isint是0,我有一个循环要求用户给出一个整数,我读取直到用户给出一个整数.我尝试这个代码给出一个字符而不是一个整数,但我有一个无限循环.该程序只是不等待提供新的输入.我的代码出了什么问题?
#include <stdio.h>
int main(void) {
int arg1;
//int arg2;
int attacknum = 1;
int isint = 1;
//printf("Insert argument attacks and press 0 when you have done this.\n");
printf("Attack %d\n", attacknum);
attacknum++;
printf("Give attacking argument:");
isint = scanf("%d", &arg1); //line 5
while(isint == 0){
printf("You did not enter a number. Please enter an argument's number\n");
isint = scanf("%d", &arg1);
printf("is int is %d\n", isint);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 当输入是一个字符时,以下简单程序将给出一个无限循环,尽管这意味着从数字中分辨出一个字符。如何scanf使用返回值测试是否假设某个字符是数字scanf?
#include <stdio.h>
int main() {
int n;
int return_value = 0;
while (!return_value) {
printf("Input a digit:");
return_value = scanf("%d", &n);
}
printf("Your input is %d\n", n);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在这个程序中,我采用了一个大小为[3][4] 的多维字符数组,只要我为每行输入 3 个字符,它就可以正常工作。
例如:如果我输入, abc abd abd我会得到相同的输出,但如果我在第一行或第二行或第三行输入更多字母,则会出现错误。
我应该如何检查二维中的空字符?
# include <stdio.h>
#include <conio.h>
# include <ctype.h>
void main()
{
int i=0;
char name[3][4];
printf("\n enter the names \n");
for(i=0;i<3;i++)
{
scanf( "%s",name[i]);
}
printf( "you entered these names\n");
for(i=0;i<3;i++)
{
printf( "%s\n",name[i]);
}
getch();
}
Run Code Online (Sandbox Code Playgroud)