2013-03-31 175 views
0

*您好! 我正在制作一个程序,用户输入一个句子和程序 打印出一个句子中有多少个字母(首都和非首都)。 我做了一个程序,但它打印出奇怪的结果。请尽快帮忙。 :)字符串,C++中的字符比较

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

    } 



} 
+1

'a Dave

+0

你能否附上“怪异的结果”? – Trinimon

回答

0
if (96<int(Sent[a])<123 || 64<int(Sent[a])<91){ 

这是使用这个标志的wrong.You不能比的。 您必须做的:

if(Sent[a] > 96 && Sent[a] < 122 || .... 
2

首先你会得到一个,只有一个单词。 cin >> Sent不会提取整行。您必须使用getline才能做到这一点。其次,您应该使用isspaceisalpha来代替字符是否为空格/字母数字符号。

第三,a < b < c基本上与(a < b) < c相同,完全不是你的意思(a < b && b < c)。

0
if (96 < Sent[a] && Sent[a]<123 || 64 < Sent[a] && Sent[a]<91) 

这是你想要的,这是因为:

96<int(Sent[a])<123 

将评估96<int(Sent[a]),为布尔的话,会比较它(即0或1)123

0

此行

if (96<int(Sent[a])<123 || 64<int(Sent[a])<91)

必须是这样的

if ((96<int(Sent[a]) && int(Sent[a])<123) || (64<int(Sent[a]) && int(Sent[a])<91))

但我建议使用在cctype头文件中定义的函数isalpha()

1

你可以做的std ::阿尔法如下:

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

    } 

这是更好地使用getline比如果输入包含空格使用cin>>

+0

*“如果输入包含空白,最好使用getline而不是使用cin。”* Nah。最好使用'getline'_on_' cin',因为'operator >>'在空白处停止。两者都在'cin';)上运行。 – Zeta

+0

@泽塔谢谢。我同意。我刚刚更新了它。 – taocp