我对该程序有疑问,我希望它只在输入中显示一次单词并在每次出现时进行计数,但它会显示输入的每个单词。
例如,如果我输入
"this should only only appear appear once"
然后我想让程序输出
this 1
should 1
only 2
appear 2
once 1
如有任何帮助,我们将不胜感激。
#include <stdio.h>
#include <string.h>
#define ROW 1000
#define COL 50
int read_input(char *str, int n);
int main(void)
{
char str[ROW];
char stringSeperate[ROW][COL] = { };
const char *s= " ,.!";
char *p;
int freq[ROW];
int i = 0;
int wordCount = 0;
int pos = 0;
read_input(str, ROW);
p = strtok(str,s);
i = 1;
while(p !=NULL) {
wordCount = i;
for(i = 0; i < wordCount; i++) {
if (strcmp(p, stringSeperate[i]) != 0)
pos = 1;
else
pos = i;
}
if (pos == 1) {
strcpy(stringSeperate[i], p);
freq[i++]++;
}
else
freq[pos]++;
p = strtok(NULL,s);
}
for ( i = 1; i <= wordCount; i++ ) {
printf("Word: %s\t Number: %d\n",stringSeperate[i], freq[i]);
}
return 0;
}
int read_input(char *str, int n)
{
int ch, i = 0;
while((ch = getchar()) != '\n') {
if ( i < n ) {
*str++ = ch;
i++;
}
}
*str = '\0';
return i;
}
最佳答案
您通过使用具有自动存储持续时间(不确定)的未初始化变量 freq
的值来调用未定义的行为。
像int freq[ROW] = {0};一样初始化它
你也应该
1.将 stringSeperate
的初始化更改为标准:不允许空初始化器,所以它应该像
char stringSeperate[ROW][COL] = {{0}};
2.删除额外的打印以匹配所需的输出:更改
printf("Word: %s\t Number: %d\n",stringSeperate[i], freq[i]);
至
printf("%s %d\n",stringSeperate[i], freq[i]);
3.检查输入的长度以免导致缓冲区溢出。改变
if ( i < n ) {
在read_input
中到
if ( i < n - 1 ) {
以便为终止空字符腾出空间。
关于统计相似的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35952555/