我是 C 编程新手,所以请原谅我的天真。以下程序在输出时无法将输入字符串的最后一个字符打印为输出字符串的第一个字符。
例如:
Enter no. of elements: 5
Enter string: hello
The reversed string is: lleh
为什么o
不打印?
#include <stdio.h>
int main() {
printf("Enter no. of elements: ");
int n;
scanf("%d", &n);
char string[10000];
printf("Enter string: ");
for (int i = 0; i < n; i++) {
scanf("%c", &string[i]);
}
printf("The reversed string is: ");
for (int i = (n - 1); i >= 0; i--) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
最佳答案
您要注意一个副作用:
在
scanf("%d", &n);
之后,输入流缓冲区中有一个挂起的换行符。当您稍后输入
n
个字符时,scanf("%c", &string[i])
首先读取挂起的换行符,然后n-1
您输入的第一个字符,输入的其余部分保留在输入缓冲区中。
scanf()
是一个非常笨重的函数。很难正确使用。
这是解决您的问题的方法:
#include <stdio.h>
int main() {
char string[10000];
int i, n, c;
printf("Enter no. of elements: ");
if (scanf("%d", &n) != 1 || n < 0 || n > 10000)
return 1;
// read and discard pending input
while ((c = getchar()) != '\n' && c != EOF)
continue;
printf("Enter string: ");
for (i = 0; i < n; i++) {
if (scanf("%c", &string[i]) != 1)
break;
}
// the above loop could be replaced with a single call to fread:
// i = fread(string, 1, n, stdin);
printf("The reversed string is: ");
while (i-- > 0) {
printf("%c", string[i]);
}
printf("\n");
return 0;
}
关于c - 为什么这个反向字符串程序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45268877/