【发布时间】:2018-09-01 14:24:19
【问题描述】:
以下程序运行时没有在屏幕上打印任何内容,可能是因为循环越过了空字符。我不明白为什么会发生这种情况,如何发生,以及如何解决。
//program to find how many word in the text doesn't contain p char
#include<stdio.h>
#include<stdbool.h>
#define space ' '
void find_word(char s[]) {
bool wordfound = false;
int i, j = 0, word = 0;
i = 0;
while (s[i]) { //s[i]!='\0' does not
if (s[i] != 'p' && s[i + 1] != space) { //for the first word
wordfound = true;
word++;
}
wordfound = false;
if (s[i] == space && s[i + 1] != space) { //for more than one word in the text
for (j = i + 1; s[j] != space; j++)
if (s[j] != 'p' && s[j + 1] != space)
wordfound = true;
}
if (wordfound) {
word++;
}
wordfound = false;
i = j;
i++;
} //end while loop
printf("Number of words not contain p character%d\n\n", word);
}
int main(void) {
char s[] = {"pppp zzzz ppp ssss dfg sfsfdsf"};
find_word(s);
return 0;
}
【问题讨论】:
-
为了便于阅读和理解:1)请遵循公理:*每行只有一个语句,并且(最多)每个语句一个变量声明。 2)单独的代码块:
forifelsewhiledo...whileswitchcasedefault通过一个空行。 3) 用 2 或 3 个空行分隔函数(保持一致) 4) 请一致地缩进代码。在每个左大括号 '{' 后缩进。在每个右大括号 '}' 之前取消缩进。建议每个缩进级别为 4 个空格。 -
你可能想查看头文件:
ctypes.h,尤其是isspace()和ispunc() -
关于:
printf("Number of words not contain p character%d",word);这会将数据留在stdout缓冲区中,直到程序退出。要将其立即显示在终端上,请以 '\n' (新行)结束格式字符串,因为这会将stdout缓冲区刷新到终端 -
当
s[i + 1]是空字符 时,if (s[i] == space && s[i + 1] != space) { for (j = i + 1; s[j] != space; j++) if (s[j] != 'p' && s[j + 1] != space)会出现问题。内部循环尝试访问外部字符串。这个内部的j循环似乎在其他情况下也会继续运行。 -
Jassim Alsokni,“单词”检测很弱。考虑
"no_spaces"、" leading_spaces"、"trailing_spaces "、" "、""。让你的字数在这种情况下起作用,然后修改代码以查找'p'。 Divide and Conquer