I want to know why it does not print the complete array with my dynamic pointer in c ++

0

When I run the program, it does not print the last line on the screen. For example, if I tell you to make room for 3 string then just ask me two times and print only 2 the first two strings that I type.

I want to know why this happens and what is the solution to this problem.

My code is as follows:

#include <iostream>
#include <string>
using namespace std;

void numeroPalabras(string &palabras,int &num, string *&p)
{
    cout << ">>: ";
    cin >> num;

    p = new string[num];

    for (int i = 0; i < num ; i++)
    {
        getline(cin, p[i]);
    }
}

void presentar(string *&p, const int &num)
{
    for (int i = 0; i < num; i++)
        cout << *p++ << endl;
}


int main()
{
    int num;
    string palabras;
    string *p;
    numeroPalabras(palabras, num, p);
    presentar(p,num);
    delete p;

    /* code */
    return 0;
}
    
asked by Mucacran 08.03.2017 в 17:22
source

1 answer

1
void numeroPalabras(string &palabras,int &num, string *&p)
{
    cout << ">>: ";
    cin >> num; // <<---

    p = new string[num];

    for (int i = 0; i < num ; i++)
    {
        getline(cin, p[i]);
    }
}

After the line that I mark you with the comment in the input buffer, you save a line break. That means that when you call getline for the first time you read a blank line.

The solution is, in this case, as simple as cleaning the input buffer:

cout << ">>: ";
cin >> num;
cin.ignore();

Another mistake you have made, this time releasing the memory:

p = new string[num];
delete p;

What is created with new[] must be released with delete[] . Otherwise you risk leaving memory gaps. The correct thing is the following:

p = new string[num];
delete[] p;

And as an additional bonus, passing the pointer to presentar as a reference to pointer is totally unnecessary, accessory and counterproductive (internally it will be managed as a double pointer). And the same for native types ... if the parameter num is read only it is preferable to pass it by value to pass it by reference (the program may end up using pointers from behind):

void presentar(string *p, const int num);

or even if you like to add protection against changes:

void presentar(const string *p, const int num)
    
answered by 08.03.2017 / 17:35
source