2016-12-05 42 views
0

ファイルから行を読み込み、ファイル内の行に基づいてASCIIシェイプを出力するプログラムを作成しています。例えば、この「S @ 6」は6×6 @の実線の二乗を意味する。私の問題は、ファイルから行を読むことができますが、ファイル内の文字をどのように区切って入力として使用するかわかりません。私はすでにシェイプを作るための関数を書いていますが、ファイルの文字を引数として渡すだけです。文字列からの文字の読み取りまたは文字列からの文字の取得

int main() 
{ 
    void drawSquare (char out_char, int rows, int width); 
    void drawTriangle (char out_char, int rows); 
    void drawRectangle (char out_char, int height, int width); 

    char symbol; 
    char letter; 
    int fInt; 
    string line; 
    fstream myfile; 
    myfile.open ("infile.dat"); 

    if (myfile.is_open()) 
    { 
     while (getline (myfile,line)) 
     { 
      cout << line << '\n'; 
     } 
     myfile.close(); 
    } 

    else cout << "Unable to open file"; 
    drawRectangle ('*', 5, 7); 

} 
+0

'のstd :: strtok'はあなたの友達です(http://en.cppreference.com/w/cpp/string/バイト/ strtok) – GMichael

+0

私はこの答えのオプション2をお勧めします:http://stackoverflow.com/a/7868998/4581301 – user4581301

答えて

0

私が正しく理解していれば、あなたの入力ファイルの形式は以下である:

@ そして、あなたは長さの値を渡すことによって、適切な関数を呼び出したいシンボルに基づきます。

あなたは、ファイルから読み込んだ行を解析することによって、これを達成することができます

const char s[2] = " ";// assuming the tokens in line are space separated 
while (getline (myfile,line)) 
{ 
    cout << line << '\n'; 
    char *token; 
    /* get the first token */ 
    token = strtok(line, s); // this will be the symbol token 
    switch(token) 
    { 
     case "s" : 
     /* walk through other tokens to get the value of length*/ 
     while(token != NULL) 
     { 
      ... 
     } 
     drawSquare(...);// after reading all tokens in that line call drawSquare function 
     break; 

     ... //similarly write cases for other functions based on symbol value 
    } 
} 
関連する問題