【问题标题】:How do I populate an array in C++?如何在 C++ 中填充数组?
【发布时间】:2020-05-31 17:44:09
【问题描述】:

好的,所以我有一个文本文件,其中只有 2 行以逗号分隔的双精度。情况将永远如此。每行都必须进入其自己的 double 类型的单独数组,稍后我将不得不使用线性搜索在另一个数组中查找一个数组。 文本文件示例:

2.5,6.7,3.4,7,6.7,6,4,5,83.6
6.4,7,8,5.3,9,76

到目前为止,我已设法提取第一行,删除分隔符并将其从字符串转换为 double 类型,但我很难将其放入数组中。 我尝试过使用 while 循环、for 循环(有时是嵌套的),但它们都不起作用。我知道应该有一个简单的解决方案,但我似乎无法掌握它或数组的概念。

我能够编码的最远距离(不会弄乱)就是简单地显示它。但我需要它在一个数组中。我的代码如下。提前谢谢你。

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{
    double array[10];
    int count = 0 ;
    string values;
    int I =0;
    ifstream inputfile.open("numbers.txt");
    if (!inputfile.is_open())
    {
        cout<<"error opening file"<<endl;
    }

    if (inputfile.good())
    {
        string line;
        string num;
        getline(inputfile,line);
        values= slime;
        string stream ss(values);
        while (getline (ss,num ,','))
        {
            cout<<stod(num)<<" ";
            //HOW DO I PUT THIS INTO THE ARRAY INSTEAD PLEASE??
        }
    }

    inputfile.close();
    return 0;
}

【问题讨论】:

    标签: c++ arrays double text-files populate


    【解决方案1】:

    几件事 - 尽量不要使用using namespace std 第二 - 你只检查inputfile.good() 相关阅读后 第三 - 你需要一个索引来遍历数组,所以我添加了随着循环递增的 I,但我没有检查它是否比你的数组长度更多,所以如果它重新添加一个检查。

    #include <iostream>
    #include <fstream>
    #include <sstream>
    #include <string>
    using namespace std;
    
    int main ()
    {
        double array[10];
        int count = 0 ;
        string values;
        int I =0;
        ifstream inputfile.open("numbers.txt");
        if (!inputfile.is_open())
        {
            cout<<"error opening file"<<endl;
        }
    
        string line;
        string num;
        getline(inputfile,line);
        values= slime;
        string stream ss(values);
        int i=0;
        while (getline (ss,num ,','),)
        {
            cout<<stod(num)<<" ";
            array[i] = stod(num);
            ++i;
        }
        inputfile.close();
        return 0;
    }
    

    【讨论】:

    • 非常感谢姚达夫!这肯定有帮助,我现在可以继续编写代码了。真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 2020-09-11
    相关资源
    最近更新 更多