2017-08-04 103 views
-4

我寫了代碼來檢查輸入,我設置的HavePunct標誌總是false。但是,當我輸入hello,world!!它將錯誤的結果返回給我。請讓我知道如果您看到我的代碼有任何問題:爲什麼我總是在我的代碼中得到「false」

#include <iostream> 
#include <string> 
#include <cctype> 
using namespace std; 

int main() { 
    string s,result_s; 
    char ch; 
    bool HavePunct = false; 
    int sLen = s.size(); 

    cout << "Enter a string:" << endl; 
    getline(cin, s); 
     //檢測字符串是否有符號 
    for (string::size_type i = 0;i != sLen; ++i) { 
     ch = s[i]; 
     if (ispunct(ch)) { 
      HavePunct = true; 
     } 
     else 
      result_s += ch; 
    } 
    if (HavePunct) { 
     cout << "Result:" << result_s; 
    } 
    else { 
     cerr << "No punction in enter string!" << endl; 
     system("pause"); 
     return -1; 
    } 
    system("pause"); 
    return 0; 
} 
+4

您是否嘗試過步進以爲他調試器了嗎? –

+3

看看你在哪裏設置'sLen'。字符串是否已填充? – NathanOliver

回答

2

您正在計算輸入任何輸入之前的行長度。因此,sLen始終爲零。移動該行,使其位於讀取輸入的行之後。

cout << "Enter a string:" << endl; 
getline(cin, s); 
int sLen = s.size(); 
+0

感謝您的幫助,我以前沒有意識到這個問題。 –

+0

@ y.ferocious,不客氣。 –

2

我不能肯定,但它似乎是因爲你的迭代器的上限由變量sLen,其中分配給被s.size()您收到一個字符串之前確定,因此有效地使你的上限0,造成您的for循環永遠不會執行。

試試這個,讓我知道:

getline(cin, s); 
int sLen = s.size(); 
for (string::size_type i = 0;i != sLen; ++i) { 
ch = s[i]; 
if (ispunct(ch)) { 
    HavePunct = true; 
    } 
else 
    result_s += ch; 
} 
相關問題