简体   繁体   English

如何将字符串转换为char矩阵

[英]How to convert a string into a char matrix

I want to put a string into a char nxn matrix, which makes the string "abcdefghi" into a 3x3 char matrix, and become {abc;def;ghi} but it does not save right. 我想将一个字符串放入char nxn矩阵中,这会使字符串"abcdefghi"变成3x3 char矩阵,并变成{abc; def; ghi},但它不能正确保存。

I try to output every i , j , ch[i][j] and s[j+i*3] in the first loop, and they look right, but in the final output, it goes wrong. 我尝试在第一个循环中输出每个ijch[i][j]s[j+i*3] ,它们看起来正确,但是在最终输出中却出错了。

#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

int main()
{
    char ch[2][2];
    string s = "abcdefghi";
    int i, j;
    for (i = 0; i < 3; i++)
    {
        for(j = 0; j < 3; j++)
        {
            ch[i][j] = s[j + i * 3];
        }
    }

    for (i = 0; i < 3; i++)
    {
        cout << ch[i] << endl;
    }
    return 0;
}

I want the ch matrix become {abc;def;ghi} but the output is {abdegi;degi;gi} 我希望ch矩阵变为{abc; def; ghi},但输出为{abdegi; degi; gi}

Your code has two problems: 您的代码有两个问题:
1. char ch[2][2]; 1. char ch[2][2]; is supposed to be char ch[3][3]; 应该是char ch[3][3];
2. You assume you can print an entire row with a single cout << ch[i] << endl; 2.您假设可以使用单个cout << ch[i] << endl;打印整个行cout << ch[i] << endl; , but the rows don't end with a '\\0' , thus cout prints everything until it hits a null. ,但行的结尾不是'\\0' ,因此cout打印所有内容,直到其为空为止。

Here's a fixed version: 这是固定版本:

#include <iostream>


int main()
{
    char ch[3][3];
    auto s = "abcdefghi";
    auto* ptr = s;
    for (auto& r1 : ch)
    {
        for (auto& r2 : r1)
        {
            r2 = *ptr++;
        }
    }

    for (const auto& r1 : ch)
    {
        for (auto r2 : r1) // char is trivial to copy
        {
            std::cout << r2;
        }
        std::cout << '\n';
    }
    std::cout << std::flush;
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM