将文件中的数据存储到数组中c ++

时间:2019-03-07 10:43:49

标签: c++ arrays file

我有以下特定代码可从文本文件中读取整数:

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>

using namespace std;

bool contains_number(const string &c);

int main()
{
    int from[50], to[50];
    int count = 0;
    {
        string line1[50];
        ifstream myfile("test.txt");

        int a = 0;

        if (!myfile)
        {
            cout << "Error opening output file" << endl;
        }

        while (!myfile.eof())
        { 
            getline(myfile, line1[a]);

            if (contains_number(line1[a]))
            {
                count += 1;
                myfile >> from[a];
                myfile >> to[a];

                //cout << "from:" << from[a] << "\n";
                //cout << "to:" << to[a] << "\n";
            }
        }   
    }    
    return 0;
}

bool contains_number(const string &c)
{   
    return (c.find_first_of("1:50") != string::npos);
}

我需要将from []和to []的这些值存储在2个数组中,以便在另一个函数中使用它们,我尝试以一种简单的方式创建2个数组并影响这些值,例如:

int x[], y[];
myfile >> from[a];
for(int i=0; i<50;i++)
{
    x[i] = from[i];
}

但是它不起作用。看来这种方式仅是读取和显示,并且一旦另一个值出现,from中的值将被删除。 有帮助吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

您不会在循环中增加数组索引a。这样会导致line[0]返回true的文件中的每一行都被to[0]from[0]contains_number覆盖。

没有理由将行保存到内存中。您可以在浏览文件时处理行(即在while循环中创建一个string line变量)。

确保正确关闭文件句柄。

除此之外,您应该在循环中检查索引范围(a <50),否则,如果文件数大于50,则可能会超出数组范围。

一种更好的解决方案是使用vectors而不是数组,尤其是在文件中可以包含任意数量的数字的情况下。

相关问题