【发布时间】:2017-05-11 12:49:22
【问题描述】:
由于数组从零开始而不是从一开始,我想在我的代码中明确说明我将向计数器 (i) 添加一来弥补这一点。但是,我的功能不是读取我目前拥有的内容。
我在编码方面比较陌生,所以我很抱歉,但我会回答任何问题;
do
{
printf("\nMax # of characters?\n");
fflush(stdin);
scanf("%d", &x);
} while (x < 1 || x > 200);
do
{
printf("\nEnter Text:\n");
enter[i] = getchar();
i = 1;
error = 0;
do
{
printf("i = %d\n", (i - 1));
c = getchar();
enter[i] = c;
i++;
} while (c != '\n');
if (i > (x + 1)) //<----------- Even though I added one because arrays start at [0]
{ // the program still tells me 'i' (counter) is one
// more than it should be
printf("Words must not be longer than %d letters\n", x);
printf("You entered %d letters\n", (i - 1)); // -1 to count for the '\n'
error = 1;
}
} while (error != 0);
printf("\nOutput: %s\n", enter);
return 0;
【问题讨论】:
-
C 使用基于 0 的数组,因此代码应始终反映这一点。您需要“添加 1”的唯一位置是在 UI 中,因此,在 printf 上执行 I+1 & x+1。
-
有效
ì的条件是i < x。您没有显示enter数组的定义,但您必须在输入字符时强制执行该条件,以免数组溢出。 (当您第一次分配enter[i] = c时,i有可能未初始化。) -
fflush(stdin)在标准中是明确未定义的行为(尽管在某些实现中受支持,但这不是可移植的)。如果您尝试清除输入流,还有其他方法可用。 -
人们通常使用
forloop 循环进入数组或类似容器,它允许声明一个计数器,指定何时停止循环并像for (int i = 0; c != '\n'; i++)那样递增计数器 -
您需要在第一次 getchar 调用之前将
i设置为0。