[英]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.我收到一个错误,也没有得到想要的 output 这里可能有什么问题。 [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'.您需要在检查空格时添加空格,并且回车的条件不太有意义,最好同时检查“\r”和“\n”。 Moreover I will suggest you to either use C++ or C mixing both will be more prone to errors此外,我建议您使用 C++ 或 C 混合两者将更容易出错
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;通过在此处输入空格常量解决了空字符常量的错误,也没有将 char ch 初始化为 'a' 并且只是声明了 ch;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.