【问题标题】:While loop runs onceWhile 循环运行一次
【发布时间】:2014-12-18 14:37:30
【问题描述】:

我正在尝试运行一个程序,该程序将重复读取用户的一封信,其中最多输入为 12。如果用户输入他们输入的哨兵值,则循环应该终止。但是,一旦在循环中读取第一个字符,它就会终止。

此外,程序会将相同的单词以相反的顺序放在另一个数组中,然后检查它们以查看第一个数组(向前读取)是否与另一个数组相同(向后读取)。如果是,则显示该单词是回文。

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main()
{
int charCount, counter, i, temp, check,check2;
char  letter[12], letter2[12];
charCount = 0;
counter = 10;
check = 0;
i = 1;
check2 = 0;

printf("Enter your sentinel value.:");
scanf_s(" %c", &letter[check2]);


while ((i<13) && (letter[i] != letter[check2]))
{
    printf("Enter individual letters in word (in order).:");
    scanf_s(" %c", &letter[i]);

    charCount++;

    if (letter[i] == letter[check2])
    {
        break;
    }
    i++;

}


printf("Letters entered:%i\n", charCount);


for (i = 0; i < charCount; i++)
{
    letter2[i] = letter[i];
}

for (i = 0; i <= (charCount / 2); i++)
{
    temp = letter2[counter];
    letter2[counter] = letter2[i];
    letter2[i] = temp;
    counter--;
}

for (i = 0; i <= charCount; i++)
{
    if (letter[i] = letter2[i])
    {
        check++;
    }
}

if (check = charCount)
{
    printf("Word is a palindrome.\n");
}

system("PAUSE");
return 0;

}

【问题讨论】:

  • 1) scanf_s(" %c", &amp;letter[check2]); --> scanf_s(" %c", &amp;letter[check2], 1);
  • 2) (i&lt;13) -> (i&lt;12)
  • 3) if (letter[i] = letter2[i]), if (check = charCount) : = --> ==
  • 4) (letter[i] != letter[check2]) : letter[i] 取消初始化。

标签: c visual-studio visual-studio-2013 while-loop


【解决方案1】:

第一次进入while循环时,字母[1]的值将被取消分配,对吗?我认为您可以将该条件从while循环中取出,因为您正在while循环内的if语句中考虑它

【讨论】:

    猜你喜欢
    • 2011-11-02
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    相关资源
    最近更新 更多