在 C 中读取没有空格的单个单词时遇到问题

问题描述 投票:0回答:1

我正在开发一个 C 程序,该程序只从用户输入中读取单个单词,不包含任何空格。这是我的代码示例:

 void handleMenu(char input[7]) {
    
        for (int i = 0; input[i]; i++) {
            input[i] = toupper((unsigned char)input[i]);
        }
    
        if (strcmp(input, "LOAD") == 0) {
            load();
        } else if (strcmp(input, "CLEAR") == 0) {
            clear();
        } else if (strcmp(input, "LIST") == 0) {
            list();
        } else if (strcmp(input, "FOUNDP") == 0) {
            foundp();
        } else if (strcmp(input, "QUIT") == 0) {
            quit();
        } else {
            printf("\nInvalid option. Please try again.\n");
        }
    }

    int main() {
        char input[7];
    
        do {
            printf("\n%s\n", "------ Command Menu ------");
            printf("%-10s %s\n", " ", "LOAD");
            printf("%-10s %s\n", " ", "CLEAR");
            printf("%-10s %s\n", " ", "LIST");
            printf("%-10s %s\n", " ", "FOUNDP");
            printf("%-10s %s\n", " ", "QUIT");
            printf("--------------------------\n");
            printf("\nChoose an option: ");
            scanf("%s", input);
            getchar();
    
            handleMenu(input);
    
        } while (strcmp(input, "QUIT") != 0);
    
        return 0;
    }

当程序询问“选择一个选项:”时 例如,我写“sdjbsfj”。 程序响应“无效选项。请重试。” 这很好。

但是如果我写“231 ajf 124” 该程序将响应“无效选项。请重试。” 3次,如果我写4个字,它会说4次错误警告,依此类推。

出了什么问题以及如何解决? 预先感谢您。

c terminal output printf
1个回答
0
投票

这是因为你误解了

scanf
的用法。此函数将字符串视为字母数字和下划线字符的任何连续集合,并忽略前面的空格。我不会扫描字符串,而是使用类似
fgets
的东西,它允许您接受整行,然后我会对其进行处理。

例如

#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

#define LINE_BUF 100
void handleMenu(char input[LINE_BUF]) {

    for (int i = 0; input[i]; i++) {
        input[i] = toupper((unsigned char)input[i]);
    }

    if (strncmp(input, "LOAD", 4) == 0) {
        printf("\nLOAD introduced\n");
    }
    else{
        printf("\nError\n");
    }
}

int main() {
    char input[LINE_BUF];

    do {
        printf("\n%s\n", "------ Command Menu ------");
        printf("%-10s %s\n", " ", "LOAD");
        printf("%-10s %s\n", " ", "CLEAR");
        printf("%-10s %s\n", " ", "LIST");
        printf("%-10s %s\n", " ", "FOUNDP");
        printf("%-10s %s\n", " ", "QUIT");
        printf("--------------------------\n");
        printf("\nChoose an option: ");
        if(fgets(input,LINE_BUF, stdin) != NULL) 
        {
            handleMenu(input);
        }
    } while (strncmp(input, "QUIT", 4) != 0 && strncmp(input, "quit", 4) != 0 );

    return 0;
}

fgets
也更安全,因为你可以指示缓冲区大小,并且不会写到最后。

© www.soinside.com 2019 - 2024. All rights reserved.