0

I can't understand why does vector empty after it's filling.

The code is:

bool fillArray (vector<int> &array)
{        
    string temp;
    getline(cin, temp);

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);
}

void showArray(const vector<int> array)
{
    for (int i = 0; i < array.size(); i ++)
        cout << array[i] << " ";
}


int main(int argc, char** argv)
{
    vector<int> array;

    while (fullArray (array))
    {}

    showArray(array);
    return 0;
}

When I input -1 the cycle breaks but the size of vector is 0, why?

Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • 1
    The parameter of `showArray` should be declared as a const reference (instead of a const value). – Philipp Aug 07 '10 at 16:49

2 Answers2

5

These lines are your problem:

    if (temp  == "-1")
       return false
    else
       return true;

    int res = atoi(temp.c_str());
    array.push_back(res);

In the case of good input, you're returning true from your fillArray method before you actually call push_back with the value on your vector.

Brent Writes Code
  • 19,075
  • 7
  • 52
  • 56
  • Is that your real code after all? The compiler issues an error because the semicolon after `return false` is missing. – Philipp Aug 07 '10 at 16:53
  • I don't understand why everyone seems to re-type their code into SO instead of copy-pasting. Not only is the `;` missing after `return false` but the call within `main()` is to some function called `fullArray()` instead of `fillArray()` – Praetorian Aug 07 '10 at 17:12
0
int res = atoi(temp.c_str());
array.push_back(res);

is never reached in your fillArray Method, because the if returns true or false

Nikolaus Gradwohl
  • 19,708
  • 3
  • 45
  • 61