c语言 - 在此程序中使用 getchar() 时无法键入任何内容



我正在学习"C程序设计语言,第二版;布莱恩·科尼根和丹尼斯·里奇。我参加了这本书的练习1-19。这个问题要求定义一个反转字符串a的函数reverse。我们必须编写一个程序,一次反转一个输入。

//This program is working on online compiler but not here
#include <stdio.h>
void reverse(char s[]);
int main(void) {
int h = 0; // sort of automatic variable just to
// keep storing characters in current line
char s[200];
char c;
for (int i = 0; i < 1000; i++)
s[i] = '';
while ((c = getchar()) != EOF) {
if (c != 'n') {
s[h++] = c;
} else {
s[h++] = c;
h = 0;
reverse(s);
for (int i = 0; i < 1000; i++)
s[i] = '';
}
}
}
void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[i--] != '')
putchar(s[i]);
printf("n");
}

因此,当我在系统上使用gcc运行此代码时,在编译时不会出现任何错误,但由于某种原因,我无法键入任何输入。然而,当我使用在线C编译器时,程序可以正确运行。

void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[i--] != '')
putchar(s[i]);
printf("n");
}

如果您对字符串索引进行后减量,那么您首先使用的是200位置的值,这是无效的(它是数组中的一个位置(,所以您做得不好。要正确执行,您需要预先定义它,如:

void reverse(char s[]) {
int i = 200;
while(i >= 0)
if(s[--i] != '')
putchar(s[i]);
printf("n");
}

但是仍然有一个错误。。。当您传递一个以null结尾的字符串时,您无法确定null…之后的数组中有什么。。。。(可以是另一个null吗?(所以你必须从字符串的开头搜索null(这很好,因为大多数时候你会给例程提供短字符串,现在你不依赖于数组大小,你假设的是常数200。一个很好的方法是使用strlen()函数,如:

void reverse(char s[]) {
int i = strlen(s);
while(i >= 0) /* ??? see below */
if(s[--i] != '')
putchar(s[i]);
printf("n");
}

然后,你所做的测试根本没有必要(你已经找到了最左边的null(:

void reverse(char s[]) {
int i = strlen(s);
while(i >= 0) /* still more below VVV */
putchar(s[--i]);
printf("n");
}

还有一个小错误。。。你必须在i <= 0时停止,而不是在i < 0时停止,因为你现在正在预先递增:

void reverse(char s[]) {
int i = strlen(s);
while(i > 0) /* here!! */
putchar(s[--i]);
printf("n");
}

相关内容

最新更新