C 为什么我的代码会从数组中打印出一些垃圾?
我目前正在学习C语言,我想创建一个反转输入的函数。下面是我写的一段代码:C 为什么我的代码会从数组中打印出一些垃圾?,c,string,stdout,C,String,Stdout,我目前正在学习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]); }
#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循环应该从输入端开始,即位于
袁辉解释得很好,所以我只对他的代码进行一些改进:
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
}
而不是从i=99开始,你必须计算出你有多少个字符,然后从这个数量开始-1。可能的重复
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
}