Reputation:
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;
}
Upvotes: 0
Views: 1127
Reputation:
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;
Upvotes: 0
Reputation: 2127
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;
}
Upvotes: 0
Reputation: 610
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;
}
Upvotes: 1