我坚持这个练习。它假设读取文本[30]并返回包含但始终返回(int)1而不是正确值的单词数。 在尝试调试它时,我在 if 语句的每个“分支”中添加了一个 printf 调用作为最后一个语句(包含在 while < / strong> loop),在 countWords 函数中。在此之后编译并执行它使程序返回正确的单词数。我很确定代码中应该有问题,但我找不到错误。如果没有, printf 以任何方式影响它吗?欢迎任何关于整个代码的建议。 问候。
int main (void)
{
void readText (char [], const int);
int countWords (char []);
void printResult (int);
const int upBound = 30;
char string[upBound];
int result;
printf ("Write a text and press 'return' an extra time when done\n\n");
readText (string, upBound);
result = countWords (string);
printf ("\nThe text is %d word(s) long.", result);
return 0;
}
接下来的两个函数读取文本。
int readLine (char line[], const int upBound)
{
static int i = 0;
char tmp;
do
{
tmp = getchar ();
if (i < (upBound - 1))
{
line[i++] = tmp;
}
}
while ((tmp != '\n'));
return i;
}
void readText (char fString[], const int upBound)
{
int readLine (char [], const int);
int i;
while ((fString[(i = readLine (fString, upBound)) - 2] != '\n')
&& (i < (upBound - 1)));
if (i == (upBound - 1)) fString [(upBound - 1)] = '\0';
else fString[--i] = '\0';
}
最后两个函数应该对单词进行计数,并分别测试字符是字母还是空格。
int countWords (char fString[])
{
bool testAlphabetic (char);
int i = 0, counter = 0;
bool lfw = true;
while (fString[i] != '\0')
{
if ((lfw) && (testAlphabetic (fString[i])))
{
++counter;
lfw = false;
++i;
printf ("1"); // This is the test
}
else if (!(testAlphabetic (fString[i])))
{
lfw = true;
++i;
printf ("2"); // This is the test
}
else
{
++i;
printf ("3"); // This is the test
}
}
return counter;
}
bool testAlphabetic (char character)
{
bool isAlphabetic;
if (((character >= 'a') && (character <= 'z')) || ((character >= 'A') && (character <= 'Z')))
{
isAlphabetic = true;
}
return isAlphabetic;
}
答案 0 :(得分:4)
bool testAlphabetic (char character)
{
bool isAlphabetic;
if (((character >= 'a') && (character <= 'z')) || ((character >= 'A') && (character <= 'Z')))
{
isAlphabetic = true;
}
return isAlphabetic;
}
您不在此处初始化isAlphabetic
。如果未执行isAlphabetic = true;
,则其值不确定。
您应该将bool isAlphabetic;
替换为bool isAlphabetic = false;
。实际上不需要变量,因为你也可以写:
bool testAlphabetic (char character)
{
return ((character >= 'a') && (character <= 'z'))
|| ((character >= 'A') && (character <= 'Z'));
}
isalpha
中的标准库函数ctype.h
基本相同。