0

我有一段代码要求用户输入,它是“字符串”类型,它是一个非常简单的过程,我希望使用 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;
            }

例如,如果用户在 Help sCommand 中键入的是 h

如果用户输入 HELP 或 Help 或 HeLp,我希望它看起来如何

sCommand 无论哪种方式都应该是“帮助”

4

2 回答 2

1

这是Boost String 算法将整个问题简化为一个表达式的另一种情况:

boost::algorithm::to_lower(sCommand)

试试 Boost 库。从长远来看,它将极大地帮助您,让您专注于真正的问题,而不是像百万分之一的程序员编写自己的“将字符串转换为小写”函数那样愚蠢。

于 2014-05-29T18:57:58.870 回答
1

当您真正想要做的是将存储在该位置的字符分配给小写版本时,您正在为一个字符分配一个字符串。

因此改变这个:

sCommand = tolower(sCommand[i], loc);

对此:

sCommand[i] = tolower(sCommand[i], loc);
//      ^^^
于 2014-05-29T18:16:16.843 回答