2017-10-24 9 views
0

Iは2×3の行列であろうよう多次元ベクトルC++

ようなマトリックスを作成しようとしています。私は、次のコード

int main() 
{ 
char c; 
//Determine OS 
#ifdef __unix 
    cout << "linux machine \n"; 
    char dirinp[50] = "~/temp/coursein/p3-in.txt"; 
    char dirout[50] = "~/temp/fileio/p3-out.txt"; 
#endif 
#ifdef _WIN32 
    cout << "windows machine \n"; 
    char dirinp[50] = "C:\\temp\\coursein\\p3-in.txt"; 
    char dirout[50] = "C:\\temp\\coursein\\p3-out.txt"; 
#endif 
//Open file 
ifstream infile, outfile; 
infile.open(dirinp); 
if (!infile) 
{ 
    cout << "Couldn't open file"; 
} 
infile.get(c); 
int col = 0, row = 0; 
while(!infile.eof()) 
{ 
    if (c == '\n') 
    { 
     col = col + 1; 
     cout << "\ncol: " << col << endl; 
    } 
    //cout << c; 
    if (isdigit(c)) 
    { 
     //cout << "its a digit"; 
     int num = c - '0'; 
     matrix[col].push_back(num); 
     cout << num << " added to matrix "; 
    } 
    infile.get(c); 
} 

この中に私の主な考え方は、あなたが改行文字を検索文字で、ファイルの文字を読んでいると、テキストファイルから動的に行列を埋めるためにしようとしています。文字が数字の場合(isdigit(c)== true)、その要素を行列のその行に押します。改行文字になったら、行列の次の垂直行に移動し、ベクトルを左から右に塗りつぶします。

+0

を終了した後、あなたの質問は何ですか?あなたのコードに何か問題がありますか?何かがうまくいかない場合は、あなたのインプットと何が起こると予想されているのか、何が起こるのかを考えてみてください。あなたはあなたの質問を編集することでこれを行うことができます。それが立てば、あなたの質問はどんな種類の質問も欠けているから話題にはならない。 – Tas

答えて

0

行列が

std::vector<std::vector<int>> matrix; 

であるならば、あなたはほとんど動作します持っているもの。

col = col + 1; 
matrix.push_back(std::vector<int>()); 

col = col + 1を交換してくださいあなたはmatrixオーバーint **、その後することができますループをしたい場合は、whileループに

int **mat = new int[matrix.size()][matrix[0].size()]; 
for (int i = 0; i < matrix.size(); i++) { 
    for (int j = 0; j < matrix[i].size(); j++) { 
     mat[i][j] = matrix[i][j]; 
    } 
}