【问题标题】:scanf and fgets in same programscanf 和 fgets 在同一个程序中
【发布时间】:2016-12-06 11:51:46
【问题描述】:
void menu() {
    int op;
    printf("\n Choose a option from below : \n\n");
    printf(" 1: Add Contact\n"
           " 2: View A Contact\n"
           " 3: View All Contacts\n"
           " 4: View All Contacts With a Common First Character\n"
           " 5: Delete All Contact\n"
           " 6: Delete A Contact\n"
           " 7: Replace A Contact Name\n"
           " 8: Replace A Contact Number\n"
           " 9: Refresh\n"
           " 10: Exit\n\n");

    printf(" Which one ? ");
    fgets(op, 5, stdin);

    switch ((int)op) {
    case 1: addrecords(); break;
    case 2: viewone(); break;
    case 3: viewall(); break;
    case 4: viewonechar(); break;
    case 5: deleteall(); break;
    case 6: deleteone(); break;
    case 7: replaceone(); break;
    case 8: replaceonenumber(); break;
    case 9: refresh(); break;
    case 10: exit(0); break;

    default:
        printf ("\n Wrong Option.\n\n");
        menu();
        break;
    }
}

void addrecords() {
    char name[50];
    char number[20];

    printf("\n\n Enter Contact Number (+880) : "); //Skips this
    fgets(number, 20, stdin);

    check(number);

    printf(" Enter Contact Name : "); //Comes in here
    fgets(name, 50, stdin);

    fp = fopen("Phonebook.txt","a");

    fprintf(fp, "%s %s\n", name, number);

    fclose(fp);

    printf("\n Contact Successfully Saved!\n Returning To Main Menu...\n\n");

    menu();
}

void check(char n[20]) {
    char name[25];
    char ncheck[20];

    fp = fopen("Phonebook.txt", "r");
    fscanf(fp, "%s %s", name, ncheck);

    while (!feof(fp)) {
        if ((strcmp(ncheck, n)) == 0) {
            printf ("\n Contact Already Exists.\n\n");
            fclose(fp);
            menu();
        } else {
            fscanf (fp, "%s %s", name, ncheck);
        }
    }
}

好的,我编辑了我的程序。我输入 1 后,程序显示错误选项。但我正在进入写一个。虽然我做得对,但为什么程序显示错误的选项?和fgets 有关系吗?现在有什么问题?

【问题讨论】:

  • 有没有办法让 scanf 不留下任何换行符?
  • 我的建议:不要使用scanf,而是将其替换为您需要编写的函数,例如int GetInteger()。将scanf ("%d",&op); 替换为op = GetInteger();GetInteger() 函数写起来很简单,大约 3-4 行代码,使用 fgetsatoi
  • 顺便说一句:请检查fopen 是否返回NULL,如果是,请不要继续,而是显示错误消息并退出。
  • @SouravGhosh。那不是我的问题。我的问题是 fgets 和 scanf

标签: c scanf fgets


【解决方案1】:

好吧,尽量改变你的程序,而不是指出其他错误或缺少错误检查......并尽量保持简单,让你了解正在发生的事情,你需要做什么是替换:

switch ((int)op) {

类似

switch (atoi(op)) {

(或结合fgets()strtol()sscanf()创建自己的get_int()

【讨论】:

    猜你喜欢
    • 2011-07-29
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多