用户定义的字符矩阵

时间:2012-03-18 08:36:01

标签: c++

来自用户输入,例如:

>~d
alg
^%r

创建方形字符矩阵的最佳方法是什么,每个输入的值都分配给相应的元素?例如在这种情况下,charArray [0] [0]将是'>'和charArray [2] [1]将是'%'等。

我使用getchar()尝试了以下方法;然而,我遇到了'\ n'留下的各种各样的问题,并认为可能有一种完全不同的方式来实现这一点要好得多。

char matrix[MAX][MAX];
char c;
int matSize;

std::cin >> matSize;

for (int i = 0; i < matSize; ++i)
    {
        int j = 0;

        while ((c = getchar()) != '\n')
        {
            matrix[i][j] = c;
            ++j;
        }
    }

2 个答案:

答案 0 :(得分:0)

当您使用C ++时,为什么不使用std :: cin和std :: string来读取空行。可能不是最好的选择,但它确实有效。

for (int i = 0; i < matSize; ++i)
{
    std::cin >> in;
    if (in.length() < matSize)
    {
        printf("Wrong length\n");
        return 1;
    }
    for (int j = 0; j < matSize; j++)
    matrix[i][j] = in[j];
}

答案 1 :(得分:0)

由于每个matrix[i]都是一个固定大小的字符数组,因此您可以轻松使用std::istream::getline

#include <iostream>
#include <istream>

#define MAX 10

int main()
{
    char matrix[MAX][MAX];
    char c;
    int matSize;

    std::cin >> matSize;
    std::cin >> c; // don't forget to extract the first '\n'

    if(matSize > MAX){ // prevent segmentation faults / buffer overflows
        std::cerr << "Unsupported maximum matrix size" << std::endl;
        return 1;
    }

    for(int i = 0; i < matSize; ++i){
        std::cin.getline(matrix[i],MAX); // extract a line into your matrix
    }


    std::cout << std::endl;
    for(int i = 0; i < matSize; ++i){
        std::cout << matrix[i] << std::endl;
    }

    return 0;
}