C++ 动态分配数组;大小由用户输入的数量设置;写入文件;

标签 c++ arrays fstream ofstream

        // 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();

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

Txt 文件输出: catsandrats 有 2 种成分。 猫

最佳答案

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

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 的数组,那么摆弄第十一个元素将产生未定义的行为。

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

但是,程序员针对这个问题提出了两种常见的解决方案:要么创建一个足够大的数组(大到足以保证不会很快越界)并记录其项目的数量,要么实现一个 linked list .

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

关于C++ 动态分配数组;大小由用户输入的数量设置;写入文件;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18235815/

相关文章:

c++ - Getline 不工作

c++ - 帮助将字符串转换为 double?

javascript - 在 JavaScript 中动态更新嵌套对象

c++ - 程序不会编译

c++ - txt文件中输出0x6efcc4

c++ - 包含 Windows 上可能存在或不存在的 header

python - 将字符串(索引)列表转换为 Numpy 数组

python - 获取 mongodb 文档中的数组项

c++ - fstream中多个get()和单个getline()的理论性能差异

c++ - 读取文本文件的值并将值写入 QDoubleSpinBox