C ++项目scanf()的 [英] C Project scanf()

查看:139
本文介绍了C ++项目scanf()的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的code,我的语句是while循环开始运行显示选项,并在第一次迭代扫描选择,但在第二次迭代的选择,当不被再次分配和previous选择记住。问题是什么 ? (我使用VS2012)

 而(!完成){
    INT选择;    的printf(\\ n -------学生信息系统主菜单-------- \\ n);
    的printf(从数据库\\ N + 1负载生);
    的printf(屏幕上的\\ N 2 - 打印现有生);
    的printf(3-添加一个新的学生\\ n);
    的printf(4删除现有的学生\\ n);
    的printf(5-查找现有的学生\\ n);
    的printf(6-退出\\ n);
    输出(====>的选择吗?);
    scanf函数(%d个,&安培;选择);    开关(选择){
      情况1:
        LoadStudentsFromDatabase();
        的printf(学生从数据库加载成功的\\ n);
        打破;      案例2:
        PrintExistingStudentsOnTheScreen();
        打破;      案例3:
        的printf(\\ nFirstName:); scanf函数(%S,s.firstName);    的printf(名字:); scanf函数(%S,s.lastName);
        的printf(ID); scanf函数(%d个,&安培; s.id);
        的printf(GPA:); scanf函数(%F,&安培; s.gpa);
        的printf(部); scanf函数(%d个,&安培; s.department);        传递addStudent(安培; S);
        的printf(1加学生\\ n);
        打破;      情况4:
        的printf(\\的NID?); scanf的(%D,和ID);
        如果(DeleteStudent(ID)){
          的printf(学生成功删除的\\ n);
        }其他{
          的printf(无法删除的学生不存在\\ n?);
        } / *最终别的* /
        打破;      情况5:
        的printf(\\的NID?); scanf的(%D,和ID);
        PS = FindStudent(ID);
        如果(PS == NULL){
          的printf(学生未找到\\ n);
        }其他{
          字符*科指南[] = {CS,EE,IE,CE,ME};
          的printf(+ -------------------- + -------------------- + ---- - + ------ + ------ + \\ n);
          的printf(|名字|姓氏| ID | GPA |部| \\ n);
          的printf(+ -------------------- + -------------------- + ---- - + ------ + ------ + \\ n);
          的printf(|%20秒| 20秒%|%6D |%6.2f | 6S%| \\ N,PS-GT&;名字,PS-GT&;姓氏,PS-GT&ID,PS-GT&; GPA,科指南[ PS-GT&;部门]);
          的printf(+ -------------------- + -------------------- + ---- - + ------ + ------ + \\ n);
        } //结束,否则
        打破;      情况6:
        做= 1;
        打破;      默认:
        的printf(!!!!!!!!!!选择无效,请重试: - ))\\ n);
        打破;
    } / *结束开关* /
  } / *结束,而* /


解决方案

其实你的code为表现符合市场预期。

的行为可以用下面的输入被再现

 姓:F
名字:L
ID:1
GPA:2
部门:D

预计的 INT 作为输入,当你在别的类型, D 在这种情况下, scanf函数不断寻找一个 INT 因为你是循环的,所以行 scanf函数(%d个,&安培;选择); 也会失败来读取 INT 不是重新分配一个新的价值,因此开关语句总是看到了上一个有效值。循环在下一读取尝试然后暂停。

要解决你的问题,你需要验证输入并转到只有当你所期望的输入是有效的下一个步骤。您可以通过检查 scanf函数女巫的返回值做到这一点是成功解析的项目数根据转换模式,你的情况要只读有一个项目。

下面是一个基本方式,您如何验证一个整数输入

  INT read_integer(字符*什么)
{
    INT I = 0;
    的printf(%S:什么);
    INT R = scanf函数(%d个,&安培; I)
    而(R == 0){
        而('\\ n'!=的getchar())
            //消耗输入的其余部分,直到LF自带(输入pressed)
            ;
        的printf(%s的输入错误,重试(R =%d)\\ n,是什么,R);
        的printf(%S:什么);
        R = scanf函数(%d个,&安培; I)
    }
    返回我;
}

在这里你怎么能读

  INT部门= read_integer(部);

您也可以写浮动类似的功能 - > 浮动read_float(字符*){...}

Here is my code, my statements is that when while loop starts to run show options and scan the selection at first iteration but in second iteration choice is not assigned again and previous selection is remembered. What is the problem ? (I am using VS2012)

while (!done){
    int choice;

    printf("\n------- STUDENT INFORMATION SYSTEM MAIN MENU --------\n");
    printf("1-Load students from the database\n");
    printf("2-Print existing students on the screen\n");
    printf("3-Add a new student\n");
    printf("4-Delete an existing student\n");
    printf("5-Find an existing student\n");
    printf("6-Quit\n");
    printf("====> Choice? ");
    scanf("%d", &choice);

    switch(choice){
      case 1:
        LoadStudentsFromDatabase();
        printf("Students loaded from database successfully\n");
        break;

      case 2:
        PrintExistingStudentsOnTheScreen();
        break;

      case 3:
        printf("\nFirstName: "); scanf("%s", s.firstName);

    printf("LastName: "); scanf("%s", s.lastName);
        printf("ID: "); scanf("%d", &s.id);
        printf("Gpa: "); scanf("%f", &s.gpa);
        printf("Department: "); scanf("%d", &s.department);

        AddStudent(&s);
        printf("1 student added\n");
        break;

      case 4:
        printf("\nID? "); scanf("%d", &id);
        if (DeleteStudent(id)){
          printf("Student deleted successfully\n");
        } else {
          printf("Failed to delete the student. Does not exist?\n");
        } /* end-else */
        break;

      case 5:
        printf("\nID? "); scanf("%d", &id);
        ps = FindStudent(id);
        if (ps == NULL){
          printf("Student not found\n");
        } else {
          char *depts[] = {"CS", "EE", "IE", "CE", "ME"};
          printf("+--------------------+--------------------+------+------+------+\n");
          printf("|    FirstName       |     LastName       |  ID  |  GPA | Dept |\n");
          printf("+--------------------+--------------------+------+------+------+\n");
          printf("|%20s|%20s|%6d|%6.2f|%6s|\n", ps->firstName, ps->lastName, ps->id, ps->gpa, depts[ps->department]);
          printf("+--------------------+--------------------+------+------+------+\n");
        } //end-else
        break;

      case 6:
        done = 1;
        break;

      default:
        printf("!!!!!!!!!! Invalid choice. Try again :-))\n");
        break;
    } /* end-switch */
  } /* end-while */

解决方案

Actually your code is behaving as expected.

The behaviour can be reproduced with the following input

FirstName: f
LastName: l
ID: 1
Gpa: 2
Department: d

Department expects an int as input, when you type in something else, d in this case, the scanf keeps looking for an int as you are looping, so the line scanf("%d", &choice); fails too to read an int and choice is not reassigned a new value, so the switch statement always sees the last valid value for choice. the loop pauses then at the next read attempt.

To solve your problem you need to validate the input and go to the next step only if the input you are expecting is valid. You can do this by checking the return value of scanf witch is the number of items successfully parsed according to the conversion patterns, in your case you want to read only one item.

Here is a basic way how you could validate an integer input

int read_integer(char* what)
{
    int i = 0;
    printf("%s: ", what);
    int r = scanf("%d", &i);
    while(r == 0) {
        while('\n' != getchar())
            // consume the rest of input until a LF comes (enter pressed)
            ;
        printf("Bad input for %s, try again (r=%d)\n", what, r);
        printf("%s: ", what);
        r = scanf("%d", &i);
    }
    return i;
}

and here how you could read Department

int department = read_integer("Department");

You could also write a similar function for float -> float read_float(char*){...}

这篇关于C ++项目scanf()的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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