c++程序,输入用户的句子并计算句子中的单词和字符数

  • 本文关键字:句子 单词 字符 计算 用户 程序 c++ c++
  • 更新时间 :
  • 英文 :


我得到一个错误,也没有得到所需的输出什么错误可能在这里。[错误]空字符常量

#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;
}

您需要添加空格,而检查空格和回车条件的意义不大,最好同时检查'r'和'n'。此外,我将建议您使用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;
}

试试这个

#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;
}

解决!

#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;
}

通过在那里输入空格常量解决了空字符常量的错误,也没有将char ch初始化为'a',只是声明了ch;

相关内容

  • 没有找到相关文章

最新更新