骑自行车虽然变量
Cycling though variables
我到目前为止已经有效了此代码,但是现在,当在多维数组中循环时,它才会存储最后一个变量。
#include <iostream>
#include <functional>
using namespace std;
int main()
{
const int columns = 5, rows = 5;
int menuSelection;
string word1 = "sloan", word2 = "horse", word3 = "eqrit", word4 = "house", word5 = "water";
string table[rows][columns];
for (auto &var : { ref(word1), ref(word2), ref(word3), ref(word4), ref(word5) })
{
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
{
string test = var;
table[i][j] = test[i];
}
}
}
for (int i = 0; i < columns; ++i)
{
for (int j = 0; j < rows; ++j)
{
std::cout << table[i][j] << ' ';
}
std::cout << std::endl;
}
}
输出为:
w w w w w
a a a a a
t t t t t
e e e e e
r r r r r
我想在数组输出的每一行上显示不同的单词:
s l o a n
h o r s e
e g r i t
h o u s e
w a t e r
如果您只关心所需的输出,那么您所做的就是很多不必要的代码。当然,要学习一些东西,您可以采用不同的较长方法来实现结果。
但是,如果您关心一个简单的解决方案,则只需要std::string
s的std::array
即可通过它们打印。
#include <iostream>
#include <array>
#include <string>
int main()
{
const std::array<std::string, 5> words { "sloan", "horse", "eqrit", "house", "water" };
for (const auto& word: words)
{
for (const char charactor: word) std::cout << charactor << " ";
std::cout << 'n';
}
return 0;
}
您正在遍历每个单词,用第一个单词中的单个字符填充整个数组,然后用第二个单词中的字符覆盖整个数组,然后是第三个单词,等等。
是的,最终,数组最终仅带有最后一个字的字符。
您需要重新考虑循环。当2足够时,您不需要3个嵌套环。
尝试更多类似的东西:
#include <iostream>
#include <string>
using namespace std;
int main() {
const int columns = 5, rows = 5;
string words[] = {
"sloan",
"horse",
"eqrit",
"house",
"water"
};
string table[rows][columns];
for (int i = 0; i < rows; ++i) {
string &test = words[i];
for (int j = 0; j < columns; ++j) {
table[i][j] = test[j];
}
}
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
std::cout << table[i][j] << ' ';
}
std::cout << std::endl;
}
return 0;
}
输出
s l o a n马E Q r i t房子水
实时演示
您的代码将循环列出字符串的列表,并在每个空间中设置每个字符
循环1
S S S S S S S S S S Sl l l l l lO O O O O Oa a a a a an n n n n
循环2
H H H H HO O O O O Or r r r r rS S S S S S S S S S Se e e e e e e e e e e e e e e e
循环3 ...
等等
尝试此代码
const int columns = 5, rows = 5;
string list[] = {"sloan", "hores", "eqrit", "house", "water"};
string table[rows][columns];
for(int i = 0; i < rows; ++i)
{
string currentString = list[i];
for(int j = 0; j < columns; ++j)
{
table[i][j] = currentString[j];
}
}
for(int i = 0; i < columns; ++i)
{
for(int j = 0; j < rows; ++j)
{
std::cout << table[i][j] << ' ';
}
std::cout << std::endl;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 尝试通过多个向量访问变量时,向量下标超出范围
- 试图让变量检查数组中的某些内容
- Cpp-Tuple使用带有变量的get
- 将包含C样式数组的对象初始化为成员变量(C++)
- 当vector是tje全局变量时,c++中vector的内存管理
- 通过多个头文件使用常量变量
- std::threads可以从Windows DLL中的全局变量创建/销毁吗?
- 执行函数时导致崩溃的变量
- 骑自行车虽然变量