C函数输入之前退出 [英] C Function exiting before input

查看:171
本文介绍了C函数输入之前退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在做一个初学者C编程类项目中,我应该做一个基本订购系统的公司。
我有一个问题与我的功能之一,它工作正常作为一个单独的程序,但作为订货程序的功能它不会让我输入一个新的项目在退出函数之前。
这似乎然而通过一切运行得(项目)之后;因为我得到的加\\ n我每次运行它​​。

I'm currently doing a project for a Beginner C programming class where i'm supposed to make a basic ordering system for a company. I've got an issue with one of my functions, it works fine as a separate program but as a function in the ordering program it won't let me input a new item before it exits the function. It seems however to run through everything after the gets(item); as I get the added \n every time I run it.

下面是我的code:

do{
printf("Menu here");
scanf("%c", &menu);
switch(menu)
{
	case 'A':
		listItem();
		break;

	case 'B':
		addItem();
		break;

	...

	case 'X':
		break;
}

printf("Press Enter to continue.");
scanf("%c%c", &enter, &enter);
system("cls");

}while(menu != 'X');


void addItem()
{
    char item[30];
    printf("\nAdd new item: ");
    gets(item);
    FILE * output;
    output = fopen("items.txt", "a");
    fputs(item, output);
    fprintf(output, "\n");
    fclose(output);
}

切换后的东西是我的老师认为​​将是一个丑陋的,但有效的方式来解决的事实,我们没有深入研究了他在这一过程被称为C输入的怪癖。

the stuff after the switch is what my teacher thought would be an ugly but effective way to solve the fact that we don't delve deeper into what he called the "quirks of C input" in this course.

我很感激任何提示和答案,并在必要时提供更多的我的code的。

I'm thankful for any tips and answers and will provide more of my code if necessary.

推荐答案

正在发生的事情是这样的:

What is happening is this:


  1. 程序打印菜单。

  2. 用户类型B <&进入GT;

  3. scanf函数 B 字符。在<输入方式> 是输入流中仍在等待

  4. 的addItem 被调用。

  5. 获得()被调用时,读取<进入> 这是仍在等待,并返回一个空行

  1. Program prints the menu.
  2. User types "B<enter>".
  3. scanf reads the B character. The <enter> is still waiting in the input stream.
  4. addItem is called.
  5. gets() is called, reads the <enter> that's still waiting, and returns an empty line.

您可以通过阅读并放弃一切直到并包括下一个换行符你阅读的菜单选择字符后修复 scanf函数

You can fix it by reading and discarding everything up to and including the next newline after you read the menu selection character with scanf:

int c;

printf("Menu here");
scanf("%c", &menu);
do {
    c = getchar();
} while (c != EOF && c != '\n');

这篇关于C函数输入之前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆