【问题标题】:C++ Dynamically Allocated Array; Size set by quantity of user input; Writing to a file;C++ 动态分配数组;大小由用户输入的数量设置;写入文件;
【发布时间】:2013-08-14 15:24:36
【问题描述】:
        // lets user input ingredients; but when "n" is inputted it terminates the loop
        string test;
        static int counter = 0;
        string* gredients = new string[counter];
        string newingredients;
        while (test != "no")
        {
            getline(cin,newingredients);
            gredients[counter] = newingredients;
            if (newingredients == "n"){test = "no";}
            counter++;
        }

        // write ingredients to file
        int counter3=1;
        ofstream ob;
        ob.open(recipeName+".txt");
        // counter - 1 is so, because i do not want it to output n into the file
        ob << recipeName << " has "<<  counter-1  << " ingredients." << endl;
        for(int a = 0; a <= counter-1  ; a++)
        {
            ob  << gredients[a] << endl;
        }
        ob.close();

当我尝试将数组写入文件时,并非我输入到数组中的所有内容都会输出到文件中。在这种情况下,我已经将两个东西输入到数组猫然后老鼠。问题是,我的程序只输出猫而不是老鼠。我能想到的唯一可能的问题是for循环设置不正确。但我认为情况并非如此,因为 for 循环中的“计数器”显然设置正确 - 该文件甚至显示数组中的事物数量。所以重申一下,为什么不是我输入到数组中的所有内容都显示在文本文件中。

文本文件输出: catandrats 有 2 种成分。 猫

【问题讨论】:

    标签: c++ arrays fstream ofstream


    【解决方案1】:

    很可能,这就是你想要做的:

    vector<string> myVector;
    string input;
    
    cin >> input;
    while (input != "n")
    {
        myVector.push_back(input);
        cin >> input;
    }
    
    ofstream output;
    output.open(recipeName + ".txt");
    
    output << recipeName << " has " << myVector.size() << " ingredients." << endl;
    for (int i = 0; i < myVector.size(); i++)
    {
        output << myVector[i] << " ";
    }
    
    output.close();
    

    数组大小是不可改变的;如果你声明一个大小为 10 的数组,那么摆弄第 11 个元素将产生未定义的行为。

    在您的程序中,您最初创建了一个大小为零的数组(首先是什么?),然后尝试将数据更改为超出其边界 - 那里存在未定义的行为。

    然而,对于这个问题,程序员已经提出了两种常见的解决方案:要么创建一个足够大的数组(足够大以保证不会很快超出范围)并保持其项目的计数,要么实现一个linked list .

    简而言之,链表是一个大小可以动态改变的数组,std::vector 暴露的行为类似于链表。

    【讨论】:

    • 我对向量不太熟悉。你能用外行的术语解释什么是向量吗?你写的可能是正确的,但我只是想了解为什么使用向量比我做的更好?
    【解决方案2】:
       static int counter = 0;
       string* gredients = new string[counter];
    

    您正在分配一个由 0 个字符串组成的数组,然后访问该数组的元素。那将是未定义的行为。

    【讨论】:

    • 这个想法是用户输入成分的数量将定义数组的大小。那不行吗?我应该用不同的方式编码吗?
    猜你喜欢
    • 2016-02-10
    • 2020-10-03
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多