为什么我的C程序在执行字符的tolower转换期间打印"(null)"?

Joh*_*nny 2 c null fgets tolower

我写了这个程序,试图更好地理解C. 它有效,但由于某种原因,在正确的输出之前打印(null).我的代码:

/* This program will take a string input input from the keyboard, convert the
string into all lowercase characters, then print the result.*/

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

int main()
{
    int i = 0;
    /* A nice long string */
    char str[1024];                               
    char c;
    printf("Please enter a string you wish to convert to all lowercase: ");

    /* notice stdin being passed in for keyboard input*/
    fgets(str, 1024, stdin);  //beware: fgets will add a '\n' character if there is room       

    printf("\nYour entered string: \n\n%s\n", str);
    printf("\nString converted to lowercase: \n\n%s\n");
    while(str[i]) { //iterate str and print converted char to screen
        c = str[i];
        putchar(tolower(c));
        i++;
    }
    putchar('\n'); //empty line to look clean
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我注意到,如果我的字符串变量被添加到最后一个printf函数,问题就会消失.

更换:

printf("\nString converted to lowercase: \n\n%s\n"); 
Run Code Online (Sandbox Code Playgroud)

printf("\nString converted to lowercase: \n\n%s\n, str");
Run Code Online (Sandbox Code Playgroud)

以下是显示问题的示例输出:

Please enter a string you wish to convert to all lowercase: THE QUICK BROWN FOX
JUMPED OVER THE LAZY DOG.

Your entered string:

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG.


String converted to lowercase:

(null)
the quick brown fox jumped over the lazy dog.

Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)

Car*_*rum 6

本打印声明:

printf("\nString converted to lowercase: \n\n%s\n");
Run Code Online (Sandbox Code Playgroud)

%s在格式字符串中有一个,但是你没有传递一个参数来匹配它.

你很幸运,0碰巧传递了,你的printf实现通过打印优雅地处理它(null).你在这里处于未定义的行为领域.

如果你打开一些警告标志,你的编译器可能会警告你这类问题.在这里的快速测试中,Clang甚至不需要任何标志:

$ clang example.c -o example
example.c:20:51: warning: more '%' conversions than data arguments [-Wformat]
    printf("\nString converted to lowercase: \n\n%s\n");
                                                 ~^
1 warning generated.
Run Code Online (Sandbox Code Playgroud)

海湾合作委员会也没有:

$ gcc example.c -o example
example.c: In function ‘main’:
example.c:20: warning: too few arguments for format
example.c:20: warning: too few arguments for format
Run Code Online (Sandbox Code Playgroud)