【问题标题】:stock data from file into arrays c++将文件中的数据存入数组c ++
【发布时间】:2019-03-07 10:43:49
【问题描述】:

我有这个特定的代码来从文本文件中读取整数:

#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 中的值将被删除。 有什么帮助吗?

谢谢。

【问题讨论】:

标签: c++ arrays file


【解决方案1】:

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

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

确保正确关闭文件句柄。

除此之外,您应该检查循环中的索引范围 (a

更好的解决方案是使用vectors 而不是数组,尤其是当您的文件可能包含任意数量的数字时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多