如何操作字符串小写并存储在同一变量中
How to manipulate a string to lower case and store in same variable
我有一段代码要求用户输入,它的类型是"string",这是一个非常简单的过程,我希望用户输入的任何内容都可以使用tolower()函数进行转换。它完全像它应该做的那样,但我似乎不能把它赋值给同一个变量。请帮忙好吗?
#include <locale>
#include <string>
#include <iostream>
//maybe some other headers, but headers aren't the problem, so I am not going to list them all
while (nCommand == 0)
{
locale loc;
string sCommand;
cin >> sCommand;
for (int i = 0; i < sCommand.length(); ++i)
{
sCommand = tolower(sCommand[i],loc);
cout << sCommand;
}
例如,如果用户在帮助命令中输入h
我希望它看起来是这样的如果用户输入HELP或者HELP或者HELP
当你真正想做的是将存储在该位置的字符赋值为小写版本时,你正在将字符串赋值给一个字符。
所以改成
sCommand = tolower(sCommand[i], loc);
:
sCommand[i] = tolower(sCommand[i], loc);
// ^^^
这是Boost字符串算法将整个问题简化为单个表达式的另一种情况:
boost::algorithm::to_lower(sCommand)
尝试Boost库。从长远来看,它会对你有很大的帮助,让你专注于真正的问题,而不是像第一百万个程序员那样写自己的"将字符串转换为小写字母"的函数。
相关文章:
- 存储变量的更有效方法是什么?
- 使用 system() 不存储变量C++?
- 在递归DP中,通过存储变量来分解递归调用:效率低下
- 使用 LDAP 存储C++变量
- 在满足特定条件时运行迭代C++以存储变量
- 使用getline解析和存储变量
- 如何存储变量的地址并使用指针打印值
- C++ / Objective-C++ - 如何在 NSDictionary 中存储C++变量?
- 如何从文件中读取并存储变量
- 指针是否延长了自动存储变量的生存期
- 如何在 INI、CFG 或 XML 文件中存储C++变量
- 如何在 c++ 中的字符串数组中存储变量
- 如何在特定偏移量处存储变量
- 如何存储变量的前一个值并更新它以进行比较
- 存储变量的有效方法是什么?(自制虚拟机)
- 在C++中存储变量
- 在c++中按值调用时,存储变量的副本
- 为什么lambda只捕获自动存储变量
- 如何在寄存器中存储c++变量
- Getline()结合cin.ignore()不存储变量?(错误)