[英]string,char comparison in c++
*Hello! *你好! I'm making program where user enters a sentence and program prints out how many letters there are in a sentence(Capital and non-capital).
我正在制作程序,用户输入一个句子,然后程序打印出句子中有多少个字母(大写和非大写)。 I made a program but it prints out weird results.Please help as soon as possible.
我编写了一个程序,但是它会打印出奇怪的结果。请尽快提供帮助。 :)
:)
include <iostream>
include <string>
using namespace std;
int main()
{
string Sent;
cout << "Enter a sentence !"<<endl;
cin>>Sent;
for(int a=0;a<Sent.length();a++){
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
cout << "this is letter"<< endl;
}else{
cout << "this is not letter"<< endl;
}
}
}
First of all you will get one and only one word. 首先,您将只得到一个单词。
cin >> Sent
won't extract the whole line. cin >> Sent
不会提取整行。 You have to use getline
in order to do this. 您必须使用
getline
才能执行此操作。
Second, you should use isspace
or isalpha
instead to check whether a character is whitespace/an alphanumeric symbol. 其次,您应该使用
isspace
或isalpha
来检查字符是否为空格/字母数字符号。
Third, a < b < c
is essentially the same as (a < b) < c
, which isn't what you meant ( a < b && b < c
) at all. 第三,
a < b < c
本质上与(a < b) < c
,这根本不是你的意思( a < b && b < c
)。
You can do the following with std::alpha: 您可以使用std :: alpha执行以下操作:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string Sent;
cout << "Enter a sentence !"<<endl;
//cin >> Sent;
std::getline (std::cin,Sent);
int count = 0;
for(int a=0;a<Sent.length();a++){
if (isalpha(Sent[a])
{
count ++;
}
}
cout << "total number of chars " << count <<endl;
}
It is better to use getline
than using cin>>
if your input contains whitespace. 如果您的输入包含空格,则使用
getline
比使用cin>>
更好。
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){
This is wrong.You can't compare using this notation. 这是错误的。您无法使用此表示法进行比较。 You must do:
您必须做:
if( Sent[a] > 96 && Sent[a] < 122 || ....
if (96 < Sent[a] && Sent[a]<123 || 64 < Sent[a] && Sent[a]<91)
This is what you want, because: 这就是您想要的,因为:
96<int(Sent[a])<123
Will evaluate 96<int(Sent[a]),
as bool, then, will compare it (that is 0 or 1) with 123. 将布尔值评估为
96<int(Sent[a]),
然后将其(为0或1)与123进行比较。
This line 这条线
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91)
must be something like this 一定是这样的
if ((96<int(Sent[a]) && int(Sent[a])<123) || (64<int(Sent[a]) && int(Sent[a])<91))
but I suggest using the function isalpha()
defined in the cctype
header file. 但是我建议使用
cctype
头文件中定义的isalpha()
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.