[英]Why does my code print out some garbage from my array?
首先,您應該在使用之前清除內存。
其次,始終在字符串末尾保留一個帶有'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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.