2012-03-18 21 views
0

从用户输入诸如矩阵?例如在这种情况下,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; 
     } 
    } 

回答

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]; 
} 
0

由于每个matrix[i]是char数组具有固定大小可以很容易地使用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; 
}