仅允许使用大写字母的字符串输入

问题描述 投票:-4回答:1

我一直在google中搜索,然后在此处创建问题,所以不要怪我。我只找到了如何转换它们要做的是,该字符串输入将仅接受大写字母,并且如果有小写字母,则将拒绝我不明白为什么它会尝试从字符串转换为int

#include <iostream>
#include <string>
int main() {
string input;
std::cout << "Enter a word";
std::cin >> input;

// this not working, I think it's allow only char type
if(!isupper(input))
{
    std::cout << "Enter capital letters";
}
}

错误:没有匹配函数可调用“ isupper(std :: string&)”如果(!isupper(输入))

/ usr / include / ctype.h:119:1:注意:参数1的未知转换是从'std :: string {aka std :: basic_string}'到'int'

c++
1个回答
0
投票
// this not working, I think it's allow only char type

是。但是您可以自己滚动1

bool isupper(std::string const& s)
{
    return std::all_of(begin(s), end(s), [](auto c){ return std::isupper(c); });
}

并使用它:

int main()
{
    std::cout << isupper("HELLO") << '\n'; // 1
    std::cout << isupper("Hello") << '\n'; // 0
    std::cout << isupper("hello") << '\n'; // 0
}

演示:https://coliru.stacked-crooked.com/a/972cc179ad86c88b


[1)或,不带lambda而是不明朗的C样式函数强制转换:

bool isupper(std::string const& s)
{
    return std::all_of(begin(s), end(s), (int (*)(int)) std::isupper);
}
© www.soinside.com 2019 - 2024. All rights reserved.