关于编程原理和C++练习的"尝试这个"练习,用于迭代
'Try This' exercise on Programming Principles and Practice Using C++, For iteration
我正在学习这本书(自学),如果你能帮我做一点"试试这个"练习,我将不胜感激。
这是我写的代码:
#include "../../../std_lib_facilities.h"
int main()
{
for (char i ='a'; i <='z'; ++i) {
int x = i;
cout << i << 't' << x << 'n';
}
keep_window_open();
return 0;
}
根据这本书,下一步是:"[…]然后修改程序,为大写字母和数字写出一个整数值表。"有没有函数可以做到这一点,或者我只需要重复从a开始的循环?感谢
是,重复从"A"到"Z"和从"0"到"9"的循环。
假设你的书中包含了一些函数(可能没有),你可以将for循环重构为它自己的函数,可能称为displayCharactersInTable,它将第一个字符和最后一个字符作为参数。这些将取代在循环中使用"a"answers"z"。因此,您的主要功能看起来像:
...
displayCharactersInTable('a', 'z');
displayCharactersInTable('A', 'Z');
displayCharactersInTable('0', '9');
...
const char lc_alphabet[] = "abcdefghijklmnopqrstuvwxyz";
const char uc_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main() {
for (const char *cur = lc_alphabet; cur < lc_alphabet + sizeof(lc_alphabet); ++cur)
std::cout << *cur << t << (int)*cur << 'n';
for (const char *cur = uc_alphabet; cur < uc_alphabet + sizeof(uc_alphabet); ++cur)
std::cout << *cur << t << (int)*cur << 'n';
return 0;
}
此代码不假设字符表示是连续的(甚至按字母顺序递增),因此它适用于所有字符编码。
int b = 97; // the corresponding decimal ascii code for 'a'
int a = 65; // the corresponding decimal ascii code for 'A'
for(int i = 0; i < 26; ++i)
cout << char('A' + i) << 't' << a << 't' << char('a' + i) << 't' << b << 'n'; //print out 'A' and add i, print out a, print out 'a' and add i, print out b
++a; //increment a by 1
++b; //increment b by 1
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- 为什么output_editor Concept不需要output_e迭代器标记
- TSP递归解的迭代形式
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 关于编程原理和C++练习的"尝试这个"练习,用于迭代