Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the last value in this specific example user input not being taken for my while loop?

I’m facing a bug where, after taking in the user input from a while loop, my code does not accept the last value. This bug happens on ONE specific example, and I have no clue why this is happening.

So, for example, the user inputs:

7  
3 1 4 0 0 2 0

The output is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

3140020

HOWEVER, with the following user input (this is the specific example):

7  
3 0 1 0 0 2 0

The output should be:

3010020

BUT, the output is instead:

301002

I can’t figure this out at all. The code is attached below:

#include <iostream>
#include <vector>
#include <math.h>
using namespace std;

// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(NULL), right(NULL)  {}
    TreeNode(int x) : val(x), left(NULL), right(NULL)  {}
};

TreeNode* construct_tree(){
    int n;
    cin >> n;
    int curr_inp;
    vector<TreeNode*> vec;
    for (int i = 0; i < n; i++) {
        cin >> curr_inp;
        cout << curr_inp; // **this is the place of bug**
        if (curr_inp != 0) 
            vec.push_back(new TreeNode(curr_inp));
        else 
            vec.push_back(NULL);
    }

    for(int i = 0; i< floor(n/2);i++ )
    {
        vec[i]->left = vec[2*i+1];
        vec[i]->right = vec[2*i+2];
    }
    cout << '\n';
    return vec[0];
}

int main() {
    TreeNode* root = construct_tree();
    return 0;
}

>Solution :

Your construct_tree() function is crashing inside of its 2nd for loop. That is preventing the output of the last character written to cout, because cout output is buffered by default, and the last character is still in the buffer and hasn’t been flushed to the console yet when the crash occurs.

cin and cout are tie()‘ed together by default, so reading input from cin will first implicitly flush cout, but there is no read from cin being done after the 1st for loop’s last iteration writes to cout.

Try adding a call to cout << flush or cout.flush() after the 1st for loop is done, before entering the 2nd for loop. Or use cout << curr_inp << flush; inside the 1st for loop. Then you will see the last character displayed.

And then, you need to fix the crash.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading