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