Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

visual c++ - I'm need to count every word, line , and character of a given string

as you can see i'm trying to get the word count, character count and line count but the below code is not working.

#include<iostream>
using namespace std;
int main()
{
char ch;
int wc=1, lc=1, cc=0;

    while((ch=cin.get())!='*')
    {
        cc++;
        if(ch==' ')
            {
                wc++;
            }
        else if(ch=='
')
            {
                wc++;
                lc++;
            }
    }    
cout<<"
 the number of character=="<<cc;
cout<<"
 the number of words=="<<wc;
cout<<"
 the number of lines=="<<lc;

return 0;
}
question from:https://stackoverflow.com/questions/65622953/im-need-to-count-every-word-line-and-character-of-a-given-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I entered your code and compiled it with g++. It is working without any problems. Can you post the error you get or did it compile ?

Maybe your visual c++ compiler is not working right. The code itself should work.


Edit: Below a different version of the above code, where no text input is threaded as zero words and EOF is also a break condition of the loop. EOF depends on your system, on Windows it is Control + z, on Linux it might be Control + d.
The input text might have multiple spaces between words. Punctuation characters and digits (0-9) are threaded as word delimiters as good as possible. Underscore, backticks, tildes and apostrophe like in "don't" are handled as part of a word.
Curly brackets are handled as part of a word to keep the code simple but normal brackets are delimiters.

    #include <iostream>
    using namespace std;
    int main()
    {
        int ch, wc=0, lc=1, cc=0, old=0;
        cout<<"Enter your text, exit with '*':
";

        while ((ch=cin.get())!='*' && ch!=EOF)
        {
            cc++;
            if (old<='?' && old!=''')
                wc += !(ch<='?' && ch!=''');
            lc += ((old=ch)=='
');
        }    
        
        cout<<"
the number of character=="<<cc
            <<"
the number of words=="<<wc
            <<"
the number of lines=="<<lc<<"
";
    
        return 0;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...