相关疑难解决方法(0)

scanf()将新行char留在缓冲区中

我有以下程序:

int main(int argc, char *argv[])
{
  int a, b;
  char c1, c2;
  printf("Enter something: ");
  scanf("%d",&a); // line 1
  printf("Enter other something: ");
  scanf("%d", &b); // line 2

  printf("Enter a char: ");
  scanf("%c",&c1); // line 3
  printf("Enter another char: ");
  scanf("%c", &c2); // line 4

  printf("Done"); // line 5

  system("PAUSE");

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如我在C书中读到的那样,作者说scanf()在缓冲区中留下了一个新的行字符,因此,程序不会在第4行停止供用户输入数据,而是将新行字符存储在c2中并移至第5行.

是对的吗?

但是,这只发生在char数据类型中吗?因为我没有int在第1,2,3行中看到数据类型的这个问题.是不是?

c scanf

71
推荐指数
5
解决办法
6万
查看次数

不接受角色

我编写了一个C程序来计算输入字符的出现次数.当我执行时,我只能输入文件名.在输入要计数的字符之前,下一个语句会执行.我得到的输出如下所示.

Enter the file name
test.txt
Enter the character to be counted 
File test.txt has 0 instances of

这是我的代码

#include<stdio.h>
#include<stdlib.h>
int main()
{
  FILE *fp1;
  int cnt=0;
  char a,ch,name[20];
  printf("Enter the file name\n");
  scanf("%s",name);
  //fp1=fopen(name,"r");
  printf("Enter the character to be counted\n");
  scanf("%c",&ch);
  fp1=fopen(name,"r");
  while(1)
  {
    a=fgetc(fp1);
    if (a==ch)
      cnt=cnt+1;
    if(a==EOF)    
      break;
  }
  fclose(fp1);
  printf("File %s has %d instances of %c",name,cnt,ch);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

怎么解决这个?

c character

0
推荐指数
1
解决办法
45
查看次数

为什么我的if/else语句不起作用?

我开始为一个小型银行帐户程序编写代码,但我的if/else语句不起作用.在循环的顶部,我scanf用来获取有关下一个需要执行哪个选项的用户输入.第一个始终有效,但在此之后,始终会打印错误语句.

例如,用户类型1.印刷的是:

case 1
ERROR, please try again
Run Code Online (Sandbox Code Playgroud)

只有案例1应该打印,为什么错误信息也会打印?我尝试使用switch case语句,但也没有用.


这是我的代码:

char num = '7';
while (1) {
    if(num == '7') {  
        printf("0. Exit\n1. Deposit\n2. Withdrawal\n3. Add account\n");
        printf("4. Remove account\n5. Balance inquiry\n6. View accounts\n");
        printf("Enter option: (0/1/2/3/4/5/6)\n");
        scanf("%c", &num);
    }
    else if (num == '0') {
        exit(0);
    }
    else if (num == '1') {
        printf("case 1\n");
        num = '7';
    }
    else if (num == '2') {
        printf("case 2\n");
        num = '7';
    }
    else …
Run Code Online (Sandbox Code Playgroud)

c user-input

-1
推荐指数
1
解决办法
92
查看次数

标签 统计

c ×3

character ×1

scanf ×1

user-input ×1