为什么我的代码从数组中打印出一些垃圾?
Why does my code print out some garbage from my array?
我目前正在学习 C,我想创建一个函数来反转输入。这是我写的一段代码:
#include <stdio.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
fgets(input, 100, stdin);
for(int i = 99; i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
这个输出是正确的,但它也打印了一些垃圾,我不明白为什么。有人可以给我解释一下吗?
这是输出:
首先,在使用前请清空内存。
其次,始终在字符串末尾保留一个值为 'NULL' 的字符。 (仅适用于您的情况,因为您没有使用 sprintf
、strcpy
... 等等。)
第三,for
循环应该从输入的末尾开始,即位于 <string.h>
上的 strlen(input)
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
memset(input, 0, sizeof(input)); // add memset() to clear memory before using it
fgets(input, 100, stdin);
for(int i = strlen(input); i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
Yuanhui 解释得很好,我就改进一下他的代码:
int main() { // No need for argc and argv unless you use them
char input[100] = {0}; // Simpler than memset
do {
// Security risk if you decide to change the size of input, so use
// sizeof input instead of hard coded value. Also, check return value.
if(!fgets(input, sizeof input, stdin)) { /* Error handling code */ }
// Overkill to use printf for a single char
for(int i = strlen(input); i > -1; i--) putchar(input[i]);
putchar('\n');
} while(!feof(stdin)) // End the loop on EOF
}
我目前正在学习 C,我想创建一个函数来反转输入。这是我写的一段代码:
#include <stdio.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
fgets(input, 100, stdin);
for(int i = 99; i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
这个输出是正确的,但它也打印了一些垃圾,我不明白为什么。有人可以给我解释一下吗?
这是输出:
首先,在使用前请清空内存。
其次,始终在字符串末尾保留一个值为 'NULL' 的字符。 (仅适用于您的情况,因为您没有使用 sprintf
、strcpy
... 等等。)
第三,for
循环应该从输入的末尾开始,即位于 <string.h>
strlen(input)
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
memset(input, 0, sizeof(input)); // add memset() to clear memory before using it
fgets(input, 100, stdin);
for(int i = strlen(input); i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
Yuanhui 解释得很好,我就改进一下他的代码:
int main() { // No need for argc and argv unless you use them
char input[100] = {0}; // Simpler than memset
do {
// Security risk if you decide to change the size of input, so use
// sizeof input instead of hard coded value. Also, check return value.
if(!fgets(input, sizeof input, stdin)) { /* Error handling code */ }
// Overkill to use printf for a single char
for(int i = strlen(input); i > -1; i--) putchar(input[i]);
putchar('\n');
} while(!feof(stdin)) // End the loop on EOF
}