【问题标题】:C Programming Passing Character FunctionC编程传递字符函数
【发布时间】:2018-08-27 14:18:18
【问题描述】:
 #include <stdio.h>
 #include <string.h>
 #define SIZE 200

 void check(char str[]);

 void check(char str[]){
        /* checking if the characters entered are digits */
        int i;
        int j=0;
        char tel[10];

        for(i = 0; str[i] != '\0'; i++){
            if(str[i] >= '0' && str[i] <= '9'){
                tel[j++] = str[i];
            }
        }
        tel[j] = '\0';

    /* checking if length of zip code  is less than 5 digits */
    if(strlen(tel) < 5)
            printf("Not enough digits on input!");


    /* if length of zip code is 5 digits */
    else if (strlen(tel) == 5){
        printf("\nProgram Output: ");
        printf("(");

        /* formating zip code with parenthesis around zip */
        for(i = 0; tel[i] != '\0' && i < 5; i++){
            printf("%c", tel[i]);
        }
        printf(")");
    };
}

int main(){

    /* variable declaration */
    char str[SIZE];

    printf("Enter a zip code: ");
    scanf("%s", str);

    check(str);

    return 0;
}

我正在编写一个简单的 C 代码,用于验证来自用户的 5 个字符的邮政编码字符串。如果少于 5 个字符,程序输出错误信息。如果正好是 5 个字符,请在邮政编码周围加上括号。

当我测试我的代码时,只有我的错误消息有效。当我输入 5 个字符时,我的“else if”参数没有被执行。这是我将 char 输入传递给我的函数的方式吗?

【问题讨论】:

  • 它对我有用.. 有什么问题?
  • 注意check()中第二个for循环的}后面的分号是多余的;它标志着一个空语句的结束。 (另外,check() 不是一个好的函数名称;它可能应该是 check_zip() 或类似名称)
  • 确保消息以换行符结尾也是一个好主意,以便及时显示输出。当您在输入前进行提示时,换行符不是一个好主意,但使用fflush(stdout) 可确保写入待处理的数据。无论如何,它可能会出现——通常情况下,标准 I/O 库会在从标准输入读取数据之前将挂起的输出刷新到标准输出,如果两者都连接到终端的话——但使用 fflush(stdout) 可以确保。
  • 抱怨:在我编辑代码之前的不稳定缩进意味着我错误地识别了 }; 所属的语句 - 它位于 else if 语句的末尾,而不是 for 循环的末尾,而是它仍然是 100% 多余的(尽管在这种情况下大多是无害的)。

标签: c function if-statement


【解决方案1】:

当我测试我的代码时,只有我的错误消息有效。当我输入 5 个字符时,我的“else if”参数没有被执行。这是我将 char 输入传递给我的函数的方式吗?

没有。这是因为您使用的是缓冲输出。 printf 将其输出存储在内部缓冲区中,直到缓冲区已满或必须打印新行 \n。您的程序在printf 有机会将缓冲区刷新到输出之前退出。您需要使用\n 终止您的最终printf

printf(")\n");

无论如何,你确实想要一个新行,否则,如果它确实打印了,下一个 shell 提示符将在同一行。

【讨论】:

  • 非常感谢您的提示和解释!!!我发布的代码实际上是我正在做的其他事情的简化项目。我按照你的建议做了,效果很好。
  • @JPham 很高兴它有帮助。如果这是正确的答案,你应该接受它。
【解决方案2】:

您的输入中似乎包含字符,而您的代码中没有注意字符。

1234a
output: Enter a zip code: Not enough digits on input!

12345
output:Program Output: (12345)

查看 check 函数中的 for 循环

【讨论】:

    【解决方案3】:

    您的问题是您可能没有传递 5 个数字,请执行以下操作,添加 antes else 以进行调试 否则printf ("%s %d", tel, strlen (tel));

    【讨论】:

      【解决方案4】:

      如果没有请尝试使用 GCC 编译器!另一种错误情况是输入错误!程序按照您的期望运行良好!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-09
        • 1970-01-01
        • 2015-01-13
        • 1970-01-01
        • 1970-01-01
        • 2017-02-27
        相关资源
        最近更新 更多