处理文件的c++

C++ dealing with files

本文关键字:c++ 文件 处理      更新时间:2023-10-16

我有一个问题,在c++工作与txt文件。首先,我想做一个程序有。cpp和。h文件…它有类和函数

我的问题是:

为例,我有一个包含5行文本(玩家名字)的TXT文件。我想让txt的每一行都是字符串变量。但是只要我想用这些新变量它们就突然消失了。

程序代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
    string line;
    int i;
    string player[5];
    ifstream myfile ("1-Efes Pilsen.txt");
    if (myfile.is_open())
    {
        while ( myfile.good() )
        {
            for (i=0;i<5;i++)
            {
                getline (myfile,line);
                player[i] = line;
            }
            // after this point I still can use new variables
        }
    }
    else cout << "Unable to open file"; 
    cout << player[1]; // <--- NOT WORKING. WHY?
    myfile.close();   
}

虽然我不清楚它是如何不起作用的,但我可以猜测文件中有更多的内容,而不仅仅是5个字符串(也许是另一个换行符),这会导致while条件评估为true,导致for循环读取5行(这将失败并且实际上没有读取任何内容),并将字符串数组中的好值替换为蹩脚的值(空字符串)。

您可能想要将条件添加到for循环本身,而不是使用外部while循环;类似以下语句:

for (i=0;i<5 && myfile.good();i++)
{
   getline (myfile,line);
   player[i] = line;
}