#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int chcount = 0, wdcount =0, count = 0;
char ch='a';
cout << "Enter your text : ";
while ( ch != '\r' )
{
ch = getche();
if ( ch !=' ' )
{
chcount++;
count++;
}
else if (count > 2)
{
wdcount++;
count=0;
}
}
cout<<"\nCount of words is: "<<wdcount+1<<"\nCount of charcters is: "<<chcount-1<<"\n";
system("pause");
return 0;}
此代码计算大小超过两个字符的单词以及用户键入的短语中所有字符的数量(忽略空格)。 问题是为什么单词计数器初始值被认为是+1而字符计数器初始值被认为是-1(你可以看到cout wdcount + 1和chcount-1)?
答案 0 :(得分:0)
经过一些尝试后,我终于得到了正确的答案我喜欢发布以帮助任何感兴趣的人...感谢所有人的帮助
#include<iostream>
using namespace std;
#include<conio.h>
int main()
{
int chcount = 0, wdcount =0, count = 0;
char ch=' ';
cout << "Enter your text : ";
while ( ch != '\r' )
{
if ( ch !=' ' )
{
chcount++;
count++;
}
else if (count > 2)
{
wdcount++;
count=0;
}
ch = getche();
}
if (count >2) //validate that last word is counted
wdcount++;
cout<<"\nCount of words is: "<<wdcount<<"\nCount of charcters is: "<<chcount<<"\n";
system("pause");
return 0;
}