C++ 文本冒险游戏 - 将单词变为大写

C++ Text adventure game - Make words upper case

基本上,我正在学习本教程:http://cplussplussatplay.blogspot.com.cy/2012/11/text-adventure-games-c-part-1.html

到现在我都明白了,除了这个:

// Make words upper case
// Right here is where the functions from cctype are used
    for(i = 0; i < words.size(); i++)
    {
        for(j = 0; j < words.at(i).size(); j++)
        {
            if(islower(words.at(i).at(j)))
            {
                words.at(i).at(j) = toupper(words.at(i).at(j));
            }
        }
    }

至此,我们有了一个充满字符的词向量。 我不明白需要两个 for 循环,也不明白 words.at(i).at(j))。 它是二维矢量还是什么?

提前致谢。

编辑:非常感谢大家的帮助!我现在明白了!这是我第一次使用 Stack Overflow,到目前为止我非常喜欢它! :)

还有一个问题出现了!

string sub_str;
vector words;
char search = ' ';



    // Clear out any blanks
    // I work backwords through the vectors here as a cheat not to       invalidate the iterator
    for(i = words.size() - 1; i > 0; i--)
    {
        if(words.at(i) == "")
        {
            words.erase(words.begin() + i);
        }

1。第二条评论是什么意思?

2.How向量中可以有空格吗?根据创作者的说法,第一个循环会清除所有空白。 这是之前的代码:

for(i = 0; i < Cmd.size(); i++)
    {
        if(Cmd.at(i) != search)
        {
            sub_str.insert(sub_str.end(), Cmd.at(i));
        }
        if(i == Cmd.size() - 1)
        {
            words.push_back(sub_str);
            sub_str.clear();
        }
        if(Cmd.at(i) == search)
        {
            words.push_back(sub_str);
            sub_str.clear();
        }
    }

再次感谢!

i是某个词的索引。 j是某个字符的索引。 该算法循环遍历每个 char 个单词,然后处理下一个单词。

第一个循环遍历 word 向量(从位置 word.size - 1 处的第一个单词到最后一个单词),然后第二个循环遍历所有单词字符。如果 i 位置的单词的 j 位置的字符是小写,则将其设为大写 ​​

我将添加注释以遍历代码:

// Make words upper case
// Right here is where the functions from cctype are used
for(i = 0; i < words.size(); i++) // for each word in the vector "words"
{
    for(j = 0; j < words.at(i).size(); j++) // for each character in the word "words[i]"
    {
        if(islower(words.at(i).at(j)))      // if the character is lower case...
        {
            words.at(i).at(j) = toupper(words.at(i).at(j)); // ...make upper case
        }
    }
}

所以外循环遍历每个单词,然后内循环遍历当前单词的每个字符,如果是小写字符,则将其更改为大写。

我认为将字符更改行设置为更有效:

words.at(i).at(i) -= 32; // ...make upper case

不需要函数调用:跳转、推送和弹出机器指令来调用toupper()。只允许在同一个函数(以及堆栈框架)中立即寻址。