什么是计数用C的话最好的方法是什么? [英] What is the best way to count words in C?

查看:191
本文介绍了什么是计数用C的话最好的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个简单的数字节目,我觉得是非常有效的。这是算话的C,还是有什么缺陷这一计划的最好方法是什么?

 的#include< stdio.h中>
         诠释CountWords(无效);
         主要()
         {
            的printf(算的话,输入字符串的\ n);
            CountWords();

         }
        INT CountWords(无效)
        {
            焦炭℃;
            INT NUM = 0;
            INT标志= 0;
             而((C =的getchar())!='\ N')
            {
              如果(C =='')
              {
                标志= 0;
              }
              否则,如果(旗== 0)
              {
                NUM ++;
                标志= 1;
              }
           }
              的printf(民为%d,NUM);
         }
 

解决方案

您计数将由一个用此程序关闭。这是因为你检查一个空间添加一个你的词汇计数。你认为将与字符串中的最后一个字?

发生

Here is a simple count word program, which i feel is very efficient. Is this the best way to count words in C, or are there any flaws in this program?

         #include <stdio.h>
         int CountWords(void);
         main()
         {
            printf("count the words and enter string\n");
            CountWords();

         }
        int CountWords(void)
        {
            char c;
            int num=0;
            int flag= 0;
             while((c=getchar())!='\n')
            {
              if(c==' ')
              {
                flag=0 ;        
              }                         
              else if(flag==0)
              {
                num++;
                flag=1;     
              }                      
           }
              printf("Num is %d",num);
         }

解决方案

Your count will be off by one with this program. This is because you are checking for a space to add one to your count of words. What do you think will happen with the last word in the string?

这篇关于什么是计数用C的话最好的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆