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))。 是 2D 矢量还是什么?
提前谢谢。
编辑:非常感谢大家的帮助!我现在明白了!这是第一次使用堆栈溢出,到目前为止我很喜欢它!:)
还有一件事,另一个问题出现了!
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.矢量中怎么会有空白?根据创建者的第一个循环清除任何空白。 这是前面的代码:
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();
}
}
再次感谢!
我将添加注释来演练代码:
// 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()
。只需允许在同一函数(因此堆栈帧)中立即寻址。
i
是某个单词的索引。j
是某个字符的索引。 该算法循环遍历一个单词的每个char
,然后处理下一个单词。
第一个循环通过你的word
向量(从第一个单词到位置word.size - 1
的最后一个单词),然后第二个循环通过所有单词字符。 如果单词位置j
位置i
处的字符为小写,则将其设置为大写
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 文本文件中的单词链表
- 使用指针从C++中的数组中获取最大值
- 不带大括号的枚举形式
- 欧拉项目#8答案是大以获得有效答案
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- 当在带有Eigen的C++中使用GDB时,我如何才能看到更多的大矩阵
- 在指针的帮助下,文本文件中单词的频率
- 为什么在浮点中从大到小会引入更多的误差
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- C++读取大文件并将其保存到字符串中,然后删除特定的随机单词
- 如何在没有分隔符的大文本文件中查找所有字典单词
- C++文字冒险游戏 - 使单词大写
- 如何使用if语句来检查字符串文字是否是某个单词或短语
- C++,用于在大文件中的行上搜索单词的算法
- 在一个非常大的文件中搜索单词
- 在函数调用中,用大括号括起值文字evalue到什么位置
- 使用c++在非常大的文本文件(10gb)中搜索多个单词是最快的方式