从文本文件读取不起作用

reading form a textfile not working

本文关键字:不起作用 读取 文件 文本      更新时间:2023-10-16

>我有一个问题。当我使用以下文本文件运行此代码时:

car
3
4
-8 7
-+--
-7 1
我尝试打印它,

它最多打印数字 7,最后 2 个字符没有打印

谁能帮我?谢谢

    string srow;
    string scolumn;
    int row = 0;
    int column = 0;
    string gametype;
    ifstream myReadFile;
    myReadFile.open("text.txt");
    if (myReadFile.is_open())
    {
        getline(myReadFile, gametype);
        getline(myReadFile, srow);
        getline(myReadFile, scolumn);
        row = stoi(srow);
        column = stoi(scolumn);
        for (i = 0; i <row; i++)
        {
            for (j = 0; j <column; j++)
            {
                myReadFile.get(ch);
                printf("%c",ch);
            }
        }
    }
    myReadFile.close();
    return 0;
}

如果 ch 是字符...您正在跳过行尾。您的文件实际上是:

car<n>
3<n>
4<n>
-8 7<n>
-+--<n>
-7 1<n>

<> 是行尾字符,因此.. 如果您读取 4 个字符 x 2 行(8 个字符(.. .您正在阅读:

12345678
-+--E-7
    ^
    |
     ----- End of line (</n)

您可以使用 getline 来避免行尾或在 for 句子中读取它,但要小心,Windows/DOS (\r( 和 Unix (( 在行尾没有相同的字符。

它给出了错误的输出,因为每行都有5字符而不是4 。您没有考虑n在行尾。最后两个字符不会打印,因为两个n是从上面两行打印的。要完成的更改包括:

Replace 
for (j = 0; j <column; j++)
with
for (j = 0; j <= column; j++)