Reading from File to STL Queue

So I have an assignment to read data from a file into an STL queue. I know how to do push into the queue but I'm not sure how to do it from a file.

Can someone please provide me an example where you read into a queue from a file that contains integers.

Thanks in advance
It's two different challenges, so separate out them in your mind.

The first challenge is given a file, can you read an integer out of it?
The second challenge is given an integer, can you push it into a queue?

It sounds like you know how to do the second challenge, so let's focus on the first one.

If your file is a sequence of space-separated integers, it's fairly easy, you just do something like:
1
2
3
std::ifstream fin("integers.txt");
int my_integer;
fin >> my_integer; // fills my_integer with a value. 


Now you have an integer in "my_integer" variable. Connect the the dots and add that integer to the queue.
Got it, thanks. So now the problem asks to do the same but with an input file that has both strings and integers.

Sample Input: 245 Geography

The thing I'm having trouble with is that I'm only allowed to use one queue

Here is the code i had for integers only.

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
int main()
{
    queue <int> a;

    ifstream inf("input.txt");
    ofstream outf("output.txt");

    if (inf)
    {
        int value;

        while (inf >> value)
        {
            a.push(value);
        }

    }

    outf << "Output: ";
    while (!a.empty())
    {
        outf << a.front() << ", ";
        a.pop();
    }

}
Last edited on
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
#include <iostream>
#include <string>
#include <utility>
#include <queue>
#include <fstream>

int main()
{
    std::ifstream in_file( "input.txt" ) ;

    // the queue contains pairs: each pair having an int and a string
    // https://en.cppreference.com/w/cpp/utility/pair
    std::queue< std::pair<int,std::string> > q ;

    int number ;
    std::string text ;
    while( in_file >> number >> text ) // for each pair read from the file
        q.emplace( number, text ) ; // place it into the queue (construct the pair in-situ)
        // https://en.cppreference.com/w/cpp/container/queue/emplace

    while( !q.empty() )
    {
        const auto& pair = q.front() ;
        std::cout << pair.first << ' ' << pair.second << '\n' ;

        /* or in C++17 (structured binding)
        const auto [ num, txt ] = q.front() ;
        std::cout << num << ' ' << txt << '\n' ;
        */  
        q.pop() ;
    }
}
Thank you, I changed some things but I got it. Thanks so much!
Topic archived. No new replies allowed.