gpt4 book ai didi

c++ - 将字符串的第一个字母大写

转载 作者:太空狗 更新时间:2023-10-29 20:36:55 24 4
gpt4 key购买 nike

我正在尝试将 std::string 的第一个字符大写,使用相同的方法 mentioned here .例如下面的程序

#include <cctype>
#include <iostream>
#include <string>

int main()
{
std::string name = "foobar";
name[0] = std::toupper(name[0]);
std::cout << name;
}

我期望输出是

Foobar

当我 compile this online (使用 GCC 4.9.2)我得到了正确的输出没有任何警告。但是,当我在 Visual Studio 2013 中编译相同的代码时,我在从 toupper

返回的分配过程中收到警告
warning C4244: '=' : conversion from 'int' to 'char', possible loss of data

根据 C++ 标准,上述方法是否有效或警告是否正确?否则这只是 Visual Studio 的错误警告吗?

最佳答案

就类型而言,警告是正确的;标准中定义的 std::toupper 的类型是:

int toupper( int ch );

主要是因为它是黑暗 C 时代的残余(cctype header 对此有所暗示)。

然而,这只是故事的一部分。 另一个 toupper 位于locale header 中:

template< class charT >
charT toupper( charT ch, const locale& loc );

这个不应该给你任何警告。如果您不确定要提供哪种语言环境,std::locale() 将为您提供默认语言环境。

关于c++ - 将字符串的第一个字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776784/

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