c - 在 C 中使用用户输入的字符串从一个函数到另一个函数

标签 c string function switch-statement

所以...主要问题是如何使用用户在另一个函数中输入的字符串?我知道在主函数中完成所有操作会容易得多,但我们被迫使用尽可能多的单独函数。提前致谢。

最佳答案

根据评论,您很可能希望在两个函数都可用的范围内声明 str:

int enterWord (char *str) {   
    ...
    scanf("%24s", str);
    ...
    return str[0];
}

int menuScan (char *str) {
    ...
}

int main (void) {

    char str[25] = {0};
    int someint;
    ...

    someint = menuScan (enterWord (str));

    return 0;
}

int main (void) {

    char str[25] = {0};
    int someint, someotherint;
    ...

    someint = enterWord (str);
    ...
    someotherint = menuScan (str);

    return 0;
}

您可能还想对用户输入进行一些额外的错误检查,例如:

int enterWord (char *str) {   

    printf ("Please enter a single word that is no more than 25 characters: ");

    if (scanf ("%24s", str))
        printf ("\nThanks! You entered:  %s", str);
    else
        return -1;

    return str[0];
}

...

int main (void) {

    char str[25] = {0};
    int someint, someotherint;
    ...

    if ((someint = enterWord (str)) = -1) {
        fprintf (stderr, "enterWord() error: input failure.\n");
        return 1;
    }
    ...
    someotherint = menuScan (str);

    return 0;
}
<小时/>

输入缓冲区中保留“\n”的剩余问题

您剩下的问题来自这样一个事实:在调用 scanf 后,您将离开 '\n' (因为按 [Enter] code>) 在输入缓冲区 stdin 中。下次程序调用 scanf 时,它会将输入缓冲区中剩余的 '\n' 作为用户输入。 (如果您检查,您会发现它使用值0xa(或10),这是换行符的值)

你有两个选择。您可以使用循环来清空 stdin:

int c;
while ((c = getchar()) != '\n' && c != EOF) {}

您还可以使用scanf的赋值抑制运算符来读取并丢弃换行符,例如:

scanf ("%24[^\n]%*c", str)

其中 %24[^\n] 读取最多 24 个字符(不包括 '\n'str 中)和 %*c 读取并丢弃单个字符(换行符)。这样,在下一次用户输入之前,您的输入缓冲区是空的。

这是一个简短的工作示例:

#include <stdio.h>

int enterWord (char *str);
void menuOptions ();
int menuScan (char *str);

int main (void) {

    char str[25] = {0};

    if (enterWord (str) == -1) {
        fprintf (stderr, "enterWord() error: input failure.\n");
        return 1;
    }

    do {
        menuOptions();
    } while (!menuScan (str));

    return 0;
}

int enterWord (char *str)
{   
    printf ("Please enter a single word that is no more than 25 characters: ");

    if (scanf ("%24[^\n]%*c", str))
        printf ("\nThanks! You entered:  %s", str);
    else
        return -1;

    return str[0];
}

void menuOptions ()
{
    printf("\n\n=========   MENU   =========\n\n");
    printf("Key     Function\n");
    printf("===     ========\n");
    printf(" C      Count the letters\n");
    printf(" V      Count the vowels\n");
    printf(" R      Reverse the word\n");
    printf(" P      Check if the word is a palindrome\n");
    printf(" W      Enter a new word\n");
    printf(" Z      Exit\n\n");
}

int menuScan (char *str)
{
    /* always initialize variables */
    char *p = str;
    char menuChoice = 0;
    int c = 0;
    int charcnt = 0;

    printf ("Please enter a character from the options above: ");
    if (!scanf ("%c%*c", &menuChoice)) {
        fprintf (stderr, "menuScan() error: input failure.\n");
        return -1;
    }
    printf ("\nYou entered: %c\n", menuChoice);

    c = menuChoice;  /* I don't like to type */

    /* validate input */
    if (c < 'A' || ('Z' < c && c < 'a') || 'z' < c) {
        fprintf (stderr, "menuChoice() error: input is not [a-z] or [A-Z]\n");
        return -1;
    }

    /* convert to lowercase */
    if ('A' <= c && c <= 'Z') c += 32;

    switch (c) {
        case 'c': 
            for (; *p; p++) charcnt++;
            printf ("\n\nThere are '%d' letters in '%s'\n", charcnt, str);
            break;
        case 'z':
            return -1;
        default : printf ("(%c) invalid choice -> try again.\n", c);
    }

    return 0;
}

编译

gcc -Wall -Wextra -finline-functions -O3 -o bin/menuscan menuscan.c

示例/使用

$ ./bin/menuscan
Please enter a single word that is no more than 25 characters: 0123456789

Thanks! You entered:  0123456789

=========   MENU   =========

Key     Function
===     ========
 C      Count the letters
 V      Count the vowels
 R      Reverse the word
 P      Check if the word is a palindrome
 W      Enter a new word
 Z      Exit

Please enter a character from the options above: c

You entered: c


There are '10' letters in '0123456789'


=========   MENU   =========

Key     Function
===     ========
 C      Count the letters
 V      Count the vowels
 R      Reverse the word
 P      Check if the word is a palindrome
 W      Enter a new word
 Z      Exit

Please enter a character from the options above: z

You entered: z

关于c - 在 C 中使用用户输入的字符串从一个函数到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34124896/

相关文章:

c - 最适合基于前缀的搜索的数据结构

iphone - 使用文本文件实时绘图

JavaScript For 循环与闭包导致 JSLint 警告

c - C 编程中如何搜索 struct 数组

java - 将字符串数组值直接传递给 setter 方法

java - java中检查两个字符串是否相等

python - 检查字符串的所有字符是否都是大写

javascript - 为什么这个带有 boolean 变量的函数不起作用?

javascript - 在同一文本区域内显示多个函数值

c - 字符串比较有问题