STL

I have this question from one of my assignments

int main(int argv, char* argc[])
{
int i;
list<int> l;
do {
cin >> i;
l.push_back(i);
} while (i!=0);
return 0;
}

Adapt the above code, so that it alternately reads ints and strings from cin, and stores them in two separate lists

I can adapt is so it reads ints and strings from cin and stores them in two separate lists but I can't seem to do it alternatively.

I need to read it alternatively for a follow on question.
Last edited on
Something like:
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
int counter = 0;

do {

    if (counter % 2 == 0) // counter is even
    {
        // read int, store it in list<int>
        int num;
        cin >> num;
        int_list.push_back(num);

        if (num == 0)
            break; // i.e. "while (i != 0)" in original code
    }
    else // counter is odd
    {
        // read string, store it in list<string>
        string str;
        cin >> str;
        string_list.push_back(str);
    }

    counter ++;

} while (true);

Not sure if there is sentinel logic for the string input, you can add that by breaking there, too.

% is "modulus", which you can think of as being the remainder.
Odd numbers and even numbers alternate, so you can use this to determine to ask for an int or a string.

Strictly speaking, you don't need the counter variable, you could alternate based on the current sum of the sizes of the two lists, but I thought this would be easier to digest.
Last edited on
Kiss it. There are times when the above alternation technique is needed, and times when you can just unroll the alternation inside the loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14

int i;
string s;
do
{
  cin >> i; 
   int_list.push_back(i);
  cin >> s;
  str_list.push_back(s);
}
while(something);


Last edited on
Thank you very much

Following you reply this is what I currently have.

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


int main(int argv, char* argc[])
{
list<int> l;
list<string> s;
int counter = 0;
do {
if (counter % 2 == 0) //counter is even
{
//read int and store in list<int>
int num;
cin >> num;
l.push_back(num);

if (num == 0);
break;
}
else // counter is odd
{
//read string and store in list<string>
string str;
cin >> str;
s.push_back(str);
}

counter++;

} while (true);

}

However, when I try to run it, it exits after one input. I am not sure if I am doing something wrong.
@QueenJJ

if (num == 0);
Try removing the semi-colon on the above line in your code. The semi-colon terminates the statement.
Last edited on
I agree with jonnin, would be simpler to just ask for a string and int every loop, breaking early if necessary.
Thank you very much, problem solved
Topic archived. No new replies allowed.