How to write program that reads a file and prints lines of symbols based on its contents?

I'm a beginner and am working on an assignment with the following prompt: "Write a program to read from a file. The file contains pairs of a number and a symbol on each line. Your program must print out the symbol number times separated by a space for each pair (number, symbol) in the input file."

For example, with an input file that looks like this:
1 x
2 *
3 !
4 $
5 #
5 O
3 @

The output would look like this:
x
* *
! ! !
$ $ $ $
# # # # #
O O O O O
@ @ @

Quite frankly, I'm not sure where to start, but I at least have this code as a base:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  string fname = "";
  do {
    cout << "Enter a compressed filename base (.cmp extension): ";
    cin >> fname;
  } while(fname == "");
  fname.append(".cmp");

  ifstream fin;
  fin.open(fname);
  if(fin.fail()) {
    cerr << "Could not open file " << fname << endl;
    return 0;
  }
Last edited on
Your "code as a base" seems way over the top for the minimal file requirements to do your problem. Just open a file; e.g.
ifstream fin( "input.txt" );

Then just keep reading an int (say, n) and a char (say, c ) until the input file is exhausted and, for each pair, use a simple loop to output c and a space n times.
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 <fstream>

using namespace std;

int main()
{
    int frequency{0};
    char character;

    ifstream myfile ("lines_of_symbols.txt");
    if (myfile.is_open())
    {
        while ( myfile >> frequency >> character )
        {
            cout << frequency << ' ' << character << " - ";
            for(int i = 0; i < frequency; i++)
            {
                cout << character << ' ';
            }
            cout << '\n';
        }
        myfile.close();
    }

    else
    {
        cout << "Unable to open file";
    }

    return 0;
}



1 x
2 *
3 !
4 $
5 #
5 O
3 @



1 x - x 
2 * - * * 
3 ! - ! ! ! 
4 $ - $ $ $ $ 
5 # - # # # # # 
5 O - O O O O O 
3 @ - @ @ @ 
Program ended with exit code: 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <fstream>
using namespace std;

struct PR
{
   int n;
   char c;
   friend istream & operator >> ( istream &in, PR &p ){ return in >> p.n >> p.c; }
   friend ostream & operator << ( ostream &out, const PR &p ){ for ( int i = 0; i < p.n; i++ ) out << p.c << ' '; return out << '\n'; }
} pr;


int main()
{
   for ( ifstream in( "symbols.txt" ); in >> pr; ) cout << pr;
}


x 
* * 
! ! ! 
$ $ $ $ 
# # # # # 
O O O O O 
@ @ @ 

Topic archived. No new replies allowed.