骑自行车虽然变量

Cycling though variables

本文关键字:变量 自行车      更新时间:2023-10-16

我到目前为止已经有效了此代码,但是现在,当在多维数组中循环时,它才会存储最后一个变量。

#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;
}