gpt4 book ai didi

c++ - 如何忽略来自 std::cin 的非字母

转载 作者:行者123 更新时间:2023-11-27 23:02:30 25 4
gpt4 key购买 nike

因此,我试图从 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;
}

编辑:这是我改进后的新代码:

#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

最佳答案

使用isalpha()查看哪些字符是字母并排除它们。

因此,您可以像这样修改您的代码:

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

int main() {

string my_str;
getline(cin, my_str);

int countOfLetters = 0;

for (size_t i = 0; i < my_str.length(); i++) { // int i produced a warning
if (isalpha(my_str.at(i))) { // if current character is letter
++countOfLetters; // increase counter by one
}
}

cout << countOfLetters;
return 0;
}

关于c++ - 如何忽略来自 std::cin 的非字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26371535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com