2014-06-18 132 views
-4

我有這樣的事情。問題是字符串只能是字母,我該怎麼做?我已經坐了幾個小時,現在找不到任何工作解決方案。我試圖從這個主題Accept only letters使用的答案,但我想我太笨了,仍然不能使它工作:(C++字符串只有字母

#include <string> 
#include <vector> 
#include <iostream> 
#include <iterator> 
#include <algorithm> 


using namespace std; 

int main(void) 
{ 
vector <string> strings; 
string line; 

do 

{ 
cout << "enter string, 'stop' stops: "; 
cin >> line; 
strings.push_back(line); 
} 

while (line != "stop"); 

vector <string> :: iterator w; 
cout << "Before sorting \n"; 
for (w=strings.begin(); w!=strings.end(); w++) 
cout << *w << endl; 

sort (strings.begin(),strings.end()); 
cout << "After sorting \n"; 
for (w=strings.begin(); w!=strings.end(); w++) 

cout << *w << endl; 

} 
+0

在while循環,你需要遍歷字符串,如果其中的字母不是你應該的字母不要將它推回到字符串的向量中。要檢查一個字母是否是字母的,你可以使用'std :: isalpha' http://www.cplusplus.com/reference/cctype/isalpha/ – 101010

+0

你的循環會更好,因爲while((std :: cin >> line)&&(line!=「stop」)){strings.push_back(line);}'。這樣你就不會獲得額外的元素,並且在使用該值之前知道讀取成功。在字符串的另一個檢查上添加字符也很容易,或者將條件組合成一個'readString'函數。 – ghostofstandardspast

+0

@ 40two,而不是自己循環,我會使用'std :: all_of'。 – ghostofstandardspast

回答

1

您需要添加驗證代碼。對於簡單的情況下,可以做 類似:

if (std::find_if(line.begin(), 
        line.end(), 
        [](unsigned char ch) { return !isalpha(ch); } 
     ) != line.end()) { 
    // not all letters 
} 

(這是真的只適合在學校項目,將用於通常的網絡編碼不 工作,UTF-8)。

+0

除了'std :: find_if'在C++之前可用之外,是否有任何理由更喜歡'std :: find_if'到'std :: all_of'(或者如果你正在測試否定的話可能是'std :: any_of') 11?對於這裏正在測試的內容,我發現這兩者略微更清晰。 – ghostofstandardspast

+0

@ghostofstandardspast只有'std :: find_if'不需要C++ 11。如果您確信C++ 11,「std :: any_of」可能是更好的選擇。 –

相關問題