Итак, я пытаюсь прочитать строку из cin, затем прокручиваю строку, чтобы подсчитать, какие символы в этой строке на самом деле являются буквами в английском алфавите. Я написал программу, которая работает очень хорошо, но я хочу знать, есть ли более эффективный способ сделать это, без перебора по всему английскому алфавиту.Как игнорировать не-буквы из std :: cin
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(int i = 0; i < my_str.length(); i++){
for(int j = 0; j < alphabet.length(); j++){
if (tolower(my_str.at(i)) == alphabet.at(j)){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
}
cout << countOfLetters;
return 0;
}
EDIT: Вот мой новый и улучшенный код:
#include <iostream>
#include <string>
using namespace std;
int main() {
string my_str; //will use to store user input
getline(cin, my_str); //read in user input to my_str
int countOfLetters = 0; //begine count at 0
string alphabet = "abcdefghijklmnopqrstuwxyz"; //the entire english alphabet
for(unsigned int i = 0; i < my_str.length(); i++){
if (isalpha(my_str.at(i))){ //tolower() function used to convert all characters from user inputted string to lower case
countOfLetters += 1;
}
}
cout << countOfLetters;
return 0;
}
enter code here
Ну Алекс, вы были первыми, так что, я думаю, вы получаете репутацию! Спасибо за короткий и сладкий ответ. Я обновил свой OP своим модным новым кодом. – FluffyKittens
@AdamJ Обратите внимание, что я фокусировался на _ "без прокрутки по всему английскому алфавиту" _. Если вы заинтересованы в том, чтобы весь цикл был короче и в стиле C++, проверьте ответ ** @ 0x499602D2 **. – AlexD