1
        // 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 循环中的“计数器”显然设置正确 - 该文件甚至显示数组中的事物数量。所以重申一下,为什么不是我输入到数组中的所有内容都显示在文本文件中。

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

4

2 回答 2

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

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

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

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

于 2013-08-14T15:43:11.703 回答
1
   static int counter = 0;
   string* gredients = new string[counter];

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

于 2013-08-14T15:32:49.523 回答