How to output text in vertical lines in c++? Beginner.

I want to make a program that can read from a text file, then output what is in the text file in vertical lines.

Example:
The text in the file is horizontal:
My dog is red.
I want it to be displayed vertically:
m
y
d
o
g
i
s
r
e
d

I already have already created part of the program to display from the text file.

I have about 5 lines that i want to be displayed vertically.


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
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>

using namespace std;

int main ()
{
	cout << "Enter filename:" << endl;
	
	char filename[500];
	ifstream bookshelf;
	cin.getline (filename, 500);
	bookshelf.open (filename);

	if(!bookshelf.is_open()){
		exit(EXIT_FAILURE);
	}
    
	char word[500];
	bookshelf >> word;
	while (bookshelf.good()){
		 cout << "\n" << word << " ";
		bookshelf >> word; 
	}

	
	system("pause");
	return 0;
}


I need help on how to get the desired output. I don't know where to start. Give me some direction as to what I need to do next. Thank you.
Last edited on
Sadly, I'm still a newbie on the C++ but as far as i think you need to use "Tokens". I hope somebody will explain it as I haven't got to them ,yet.
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 <string>
#include <vector>
#include <fstream>
#include <iostream>

int main()
{
    std::vector<std::string> lines_in_file ;
    std::size_t max_line_size = 0 ;

    // read all the lines in the file into lines_in_file
    // updating max_line_size to be the size of the longest line
    {
        std::ifstream file( __FILE__ ) ;
        std::string line ;
        while( std::getline( file, line ) )
        {
            lines_in_file.push_back(line) ;
            if( max_line_size < line.size() ) max_line_size = line.size() ;
        }
    }

    // print lines_in_file, column by column
    for( std::size_t i = 0 ; i < max_line_size ; ++i )
    {
        for( const std::string& line : lines_in_file )
            std::cout << ( line.size() > i ? line[i] : ' ' ) << ' ' ;
        std::cout << '\n' ;
    }
}
Thank You JLBorges. Your solution works great. I am a beginner so I still do not understand most of what is going on in the code. Can you please explain how it works?
Do you know what std::vector<> and std::string are?

If not, read up on them:
http://www.mochima.com/tutorials/vectors.html
http://www.mochima.com/tutorials/strings.html

Once you have done that, just bump this thread; the loop in lines 24-29 which does the printing would then be easily explained.



Last edited on
Will do. Thanks again.
Topic archived. No new replies allowed.