回 帖 发 新 帖 刷新版面

主题:[讨论]判断一个句子的单词个数

 //输入一个句子,判断其单调的个数 

//运行过程中总是出错,希望各位高手指点.
#include<iostream>
#include<cstring>
using namespace std;

class WORDNUM
{
      public:
             WORDNUM( )
             {
                      str[0]='\0';
                      count=0;
                      }
             void input();  //输入一个句子 
             void process();//判断有多少个单词 
             void print();  //输出单词数量 
             
      private:
             char str[100];  //存放字符串str 
             int count;      //存放字符串str中的英文个数 
              };
           
void WORDNUM::input()
{
     char * inputString;
     cout<<"Please input an English sentence:";
     cin>>inputString;
     int length;
     length = strlen(inputString);
     length = (length<100? length: 99);
     strncpy(str,inputString, length);
     str[length]='\0';
     cout<<str<<endl;
    
     }
 
void WORDNUM::process()
{
     bool word=true;  //word为状态标题,标记一个单词的开始  
     int len;
     len=strlen(str);
     
     for(int i=0; i<len; i++)
     {
             if( ( (str[i]>'a' && str[i]<'z')  || (str[i]>'A' && str[i]<'Z' ) ) && word )
             {
                 count++;
                 word=false;
                 }
             else if(str[i] == ' ')
             {
                  word=true;
                  }
                  }
                  }
void WORDNUM::print()  
{
     cout<<str<<endl;
     cout<<"Number of it = "<<count<<endl; 
     }   
int main()
{
    WORDNUM a;
    a.input();
    a.process();
    a.print();
    
    

      // system("PAUSE");
       return 0;
}

回复列表 (共2个回复)

沙发

cin>>inputString; //inputString没有分配空间;对一个char *型的指针,使用的时候要分配空间,或者让其指向一个已经分配的空间.

板凳


   char * inputString;
     inputString= new char [100];
     cout<<"Please input an English sentence(less than 100 words):";
     cin.getline(inputString, 99, '\n');
     int length;
     length = strlen(inputString);
     length = (length<100 ? length : 99);
     strncpy(str,inputString, length);
     
     str[length]='\0';  

我改成这样,有没有更好的方法,可以给些好的代码吗?我很菜呀.希望得到更多帮助.

我来回复

您尚未登录,请登录后再回复。点此登录或注册