我有這樣的事情。問題是字符串只能是字母,我該怎麼做?我已經坐了幾個小時,現在找不到任何工作解決方案。我試圖從這個主題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;
}
在while循環,你需要遍歷字符串,如果其中的字母不是你應該的字母不要將它推回到字符串的向量中。要檢查一個字母是否是字母的,你可以使用'std :: isalpha' http://www.cplusplus.com/reference/cctype/isalpha/ – 101010
你的循環會更好,因爲while((std :: cin >> line)&&(line!=「stop」)){strings.push_back(line);}'。這樣你就不會獲得額外的元素,並且在使用該值之前知道讀取成功。在字符串的另一個檢查上添加字符也很容易,或者將條件組合成一個'readString'函數。 – ghostofstandardspast
@ 40two,而不是自己循環,我會使用'std :: all_of'。 – ghostofstandardspast