2013-03-31 176 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