2016-12-05 403 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 
    } 
}