简体   繁体   中英

c++ program that inputs a sentence from the user and counts the number of words and characters in the sentence

I am getting an error and also not getting the desired output what wrong could be here. [Error] Empty Character Constant

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    int countch=0;
    int countwd=1;

    cout<<"Enter a sentence: "<<endl;
    char ch='a';

    while(ch!='\r')
    {
        ch=getche();

        if(ch=='')
        countwd++;
      
        else
        countch++;
        
    }
    cout<<"\nWords = "<<countwd<<endl;
    cout<<"\nCharacters = "<<countch-1<<endl;

    return 0;
}

You need to add space while checking for space and condition for carriage return makes less sense it's better to have check for both '\r' and '\n'. Moreover I will suggest you to either use C++ or C mixing both will be more prone to errors



int main()
{
    int countch=0;
    int countwd=1;

    cout<<"Enter a sentence: "<<endl;
    char ch='a';

    while(ch!='\r' && ch!='\n')
    {
        ch=getche();

        if(ch==' ')
        countwd++;
      
        else
        countch++;
        
    }
    cout<<"\nWords = "<<countwd<<endl;
    cout<<"\nCharacters = "<<countch-1<<endl;

    return 0;
}

Try This

#include <iostream>
using namespace std;

int main(){

    int character_counter = 0, word_counter = 0;

    cout << "Enter a sentence: " << endl;
    char character, previous_character;

    while (character != '\n'){
        scanf("%c", &character);

        if (character == 32){
            if (character_counter > 0 && previous_character != 32)
                 word_counter++;
        }else{
            if (character != '\n' && character != 32)
                character_counter++;
        }

        previous_character = character;
   }

    if (character_counter > 0){
        word_counter += 1;
    }

    cout << "\nWords = " << word_counter << endl;
    cout << "\nCharacters = " << character_counter << endl;

    return 0;
}

Solved!

#include <iostream>
#include <conio.h>
using namespace std;

int main()
{
    int countch=0;
    int countwd=1;
    cout<<"Enter a sentence: "<<endl;
    char ch;
    while(ch!='\r')
    {
        ch=getche();
        if(ch==' '){
            countwd++;
        }else{
            countch++;
        }
    }
    cout<<"\nWords = "<<countwd<<endl;
    cout<<"Characters = "<<countch-1<<endl;
    return 0;
}

Error for empty character constant solved by entering a space constant there, also not initialized the char ch as 'a' and just declared ch;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM