我写了这个程序,试图理解C稍微好一点。它可以工作,但由于某种原因,在正确输出之前打印(null)。我的代码:为什么我的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;
}
顺便说一句,我注意到,当如果我的字符串变量添加到最后一个printf函数,问题消失。
替换:
printf("\nString converted to lowercase: \n\n%s\n");
与
printf("\nString converted to lowercase: \n\n%s\n, str");
下面是该问题的样本输出:
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 . . .
我刚才试了一下你PROG没有看到任何(空) – Satya
@Satya,这个程序会导致未定义的行为,所以如果你尝试它,你可能会(可能?)看到不同的行为。 –
非常感谢@CarlNorum对这样美丽的解释 – Satya