2012-03-18 22 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; 
}