Program terminates after inputting vector elements

Hi everyone,

I hope you can forgivably help me answer this kinda noob question. I was coding Ex 8 Chap 5 of Stroustrup's C++ Principles book. Long story short, if I cin the number of vector elements (highlighted below) before cin the elements themselves, then the code works (as below). But if I cin the number of elements AFTER cin the elements, then the code just terminate after I key in the elements, saying "Insufficient value". Can someone pls explain to me the reason behind such anomaly. Thank you!

The 'working' code with output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include "std_lib_facilities.h"
#include <iostream>

int main() try {
    vector<int> num_list;
    int num;
    int amt;
    int sum = 0;

    cout << "How many numbers you wish to sum? ";
    cin >> amt;
    if (amt < 1)
        error("At least 1 value required!");

    cout << "Enter the elements: ";
    while (cin >> num) {
        num_list.push_back(num);
    }

    if (amt > num_list.size())
        error("insufficient values!");

    for (int i = 0; i < amt; i++) {
        sum += num_list[i];
    }
    cout << "The sum of numbers is: " << sum << '\n';
    return 0;
}

catch (exception& e) {
    cerr << "Error: " << e.what() << endl;
    keep_window_open();
    return 1;
}
catch (...) {
    cerr << "Unknown exception!\n";
    return 2;
}



[output]How many numbers you wish to sum? 3
Enter the elements: 1 2 3 4 5 |
The sum of numbers is: 6


The 'not working' code with output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "std_lib_facilities.h"
#include <iostream>

int main() try {
    vector<int> num_list;
    int num;
    int amt;
    int sum = 0;

    cout << "Enter the elements: ";
    while (cin >> num) {
        num_list.push_back(num);
    }

    cout << "How many numbers you wish to sum? ";
    cin >> amt;
    if (amt < 1)
        error("At least 1 value required!");
    if (amt > num_list.size())
        error("insufficient values!");

    for (int i = 0; i < amt; i++) {
        sum += num_list[i];
    }
    cout << "The sum of numbers is: " << sum << '\n';
    return 0;
}

catch (exception& e) {
    cerr << "Error: " << e.what() << endl;
    keep_window_open();
    return 1;
}
catch (...) {
    cerr << "Unknown exception!\n";
    return 2;
}



Enter the elements: 1 2 3 4 5 |
How many numbers you wish to sum? Error: Insufficient value!
Please enter a character to exit


I use Dev C++ 5.11 with std_lib_facilities.h library.

Last edited on
closed account (48bpfSEw)
please give us next time a compileable source!


while(cin>>num) has no end-criteria!

try this:

1
2
3
4
5
        cout << "Enter the elements: ";
        for (int i=0;i<amt;i++ ) {
            cin >> num;
            num_list.push_back(num);
        }




and format your code with http://format.krzaq.cc/
and use the code command (look to the right when you answer or edit your text)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <vector>
#include <iostream>

using namespace std;

int main(void) {
    try {
        vector<int> num_list;
        int num;
        int amt;
        int sum = 0;
    
        cout << "How many numbers you wish to sum? ";
        cin >> amt;
        if (amt < 1) {
            cout << "error: At least 1 value required!" ;
            exit(-1);
        }
        
        cout << "Enter the elements: ";
        for (int i=0;i<amt;i++ ) {
            cin >> num;
            num_list.push_back(num);
        }
    
        if (amt > num_list.size()) {
            cout << "error:insufficient values!" ;
            exit(-1);
            }
    
        for (int i = 0; i < amt; i++) {
            sum += num_list[i];
        }
        cout << "The sum of numbers is: " << sum << '\n';
        return 0;
    }
    
    catch (exception& e) {
        cerr << "Error: " << e.what() << endl;
        // keep_window_open();
        return 1;
    }
    catch (...) {
        cerr << "Unknown exception!\n";
        return 2;
    }
    
    return 0;
}
But if I cin the number of elements AFTER cin the elements, then the code just terminate, saying "Insufficient value".

You only show the code that you said works. How 'bout we see the code that doesnt' work? I would almost bet that however you're terminating the loop, whether entering a non-numeric value or faking an end-of-file marker, that you're not clearing the state of the input stream or removing the offending content from the stream.

while(cin>>num) has no end-criteria!

Sure it does.

At least if all the numbers are valid though.

You make no sense.
I fail to see how that "clarifies" anything. You still make no sense. The condition that is the subject of this discussion currently can evaluate to false (ie. has end-criteria in the parlance above) and it will continue to do so whether "all the numbers are valid" or not.
You only show the code that you said works. How 'bout we see the code that doesnt' work?


please give us next time a compileable source!


Hi. Thanks for your advice. I have edited my post to make the codes look more readable and included the not working version. Hope you can gimme some tips!
closed account (48T7M4Gy)
while(cin>>num) has no end-criteria

As brutal a stop that it is this does have a very simple end condition as explained.

The question might arise about any follow on error trapping, exception handling or stream recovery action implemented, even the instructions to the user before data entry, ie Enter a any character to bail out., it will clearly do it's (brutal) job.

it's not the most gentle way to stop but an abrupt standstill is still an end.

@OP:

This has been modified not to use the "std_lib_facilities.h" and simplified a bit. Depending on how you're ending the loop you may need to uncomment line 20.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <vector>

using std::cout;
using std::cin;
using std::vector;

int main() {
    vector<int> num_list;
    int num;
    int amt;
    int sum = 0;

    cout << "Enter the elements: ";
    while (cin >> num) {
        num_list.push_back(num);
    }

    cin.clear();                    // clear error state on stream
    //cin.ignore(1000, '\n');         // remove contents of current line

    cout << "How many numbers you wish to sum? ";
    cin >> amt;

    for (int i = 0; i < amt; i++) {
        sum += num_list[i];
    }
    cout << "The sum of numbers is: " << sum << '\n';
    return 0;
}
This has been modified not to use the "std_lib_facilities.h" and simplified a bit. Depending on how you're ending the loop you may need to uncomment line 20.


Thank you good sir. Your suggestion works really well :D.
closed account (48T7M4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <vector>
#include <iostream>

using namespace std;

int main()
{
    vector<int> num_list;
    
    int num = 0;
    int amt = 0;
    int sum = 0;
    
    cout << "How many numbers you wish to sum? ";
    while(!(cin >> amt) or amt < 0 )
    {
        cout << "You have decided to exit.\n" ;
        exit(-1); // <-- So no need to clear stream
    }
    
    cout << "Enter the elements: ";
    for (int i=0;i<amt;i++ )
    {
        while(!(cin >> num))
        {
            cout << "\nMust enter an integer\n";
            cin.clear();
            cin.ignore(256,'\n');
        }
        num_list.push_back(num);
    }
    
    for (int i = 0; i < amt; i++)
    {
        sum += num_list[i];
    }
    cout << "The sum of numbers is: " << sum << '\n';
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.