[英]weird behaviour when using getchar, to count number of chars in a word
我目前正在通过K&R工作,在搜索网络,再次尝试并搜索更多内容后,我陷入了困境,我已经向stackoverflow寻求帮助!
任务是创建一个直方图,该直方图汇总每个单词中字母的数量,然后将信息显示为直方图。
我已经弄清楚了直方图部分,但是我在计算单词时遇到了麻烦。
当我输入几个单词时,请按Ctrl + D发送EOF,并打印每个字符输入的出现次数。 我以index [0]的大值返回了noramlly arround'15773951'
只是为了澄清我的代码将继续添加到wc中,该值用于对字符进行计数直到找到空格,换行符或制表符为止。然后它将使用数组存储通过增加索引位置来存储每个单词大小的次数。等于字长。
int main(void){
int c, i, status, wc;
int numbers[array_size];
wc = 0; //used to count number of chars
//innitialize array
for(i=1; i<array_size; i++)
numbers[i] = 0;
/*start counting letters*/
while((c = getchar()) != EOF){
/*check if c is a space*/
if((c=' ')||(c='\t')||(c='\n')){
numbers[wc-'1']++;
wc = 0;
}else{
++wc;
}
}
printf("word size occured: ");
for(i=0;i<array_size;i++)
printf("%d\n", numbers[i]);
}
有代码,任何人都可以向我解释为什么这种情况持续发生,这也是输出示例:
word size occured: 15773951
0
0
0
0
0
0
0
0
0
好的,所以:
1。
// Here you subtract from wc the integer value of the
// character '1' (which is ~49)
numbers[wc-'1']++;
应该
numbers[wc-1]++;
2。
// The array starts at index 1, ignoring the very first one ie. zero
for(i=1; i<array_size; i++)
应该
for(i=0; i<array_size; i++)
3。
// Here you assign the value ' ' to the variable c, which is equivalent to do:
// if((' ')||('\t')||('\n')){ which is equivalent to do:
// if((' ' != 0)||('\t' != 0)||('\n' != 0)){ which is always true
if((c=' ')||(c='\t')||(c='\n')){
应该
if((c==' ')||(c=='\t')||(c=='\n')){
您正在混合分配和比较以求平等...。
if((c=' ')||(c='\t')||(c='\n')){
应该
if((c==' ')||(c=='\t')||(c=='\n')){
绝对,您应该为此发出编译器警告...使用gcc,应在命令行中添加-Wall,因此您无需再次调试。
有关所有可用警告选项的详细信息,请参见gcc警告选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.