limiting string size to 60 characters

I am trying to read a file and display it. However, it can only display up to 60 characters per line (including blank spaces). This seems like it would be easy but i can not figure it out. I have tried display.resize(60), tried string display[i][60] ( i being the lines and 60 being the amount of characters per line). Anyway if any one can point me in the right direction i would greatly appreciate it.

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
  void display()
{

	int count = 0;
	ifstream infile;
	string display;
	//int n = 60;
	//streamsize n;
	display.resize(60);
	infile.open("input.txt");

	if (infile.fail())
		cout << " Error opening text file.\n";
	else
	{

		while (!infile.eof())
		{
			getline(infile, display);
			cout << display << setw(5) << endl;
		}

	}
	system("pause");
}
Here's one way:

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
#include <iostream>
#include <string>

void formatted_output(std::istream & in, std::ostream& out, std::size_t maxCharsPerLine)
{
    bool done = false;
    unsigned charsInLine = 0;

    std::string token;
    while ( in >> token )
    {
        std::size_t newLineSize = charsInLine + token.size();
        if (newLineSize <= maxCharsPerLine)
        {
            out << token;
            if (newLineSize == maxCharsPerLine || newLineSize+1 == maxCharsPerLine)
            {
                out << '\n';
                charsInLine = 0;
            }
            else
            {
                out << ' ';
                charsInLine += token.length() + 1;
            }
        }
        else
        {
            out << '\n';
            out << token << ' ';
            charsInLine = token.length() + 1;
        }
    }

    out << '\n';
}


http://ideone.com/UOJ5h5

Of course, it doesn't handle the case where a line of text is longer than 60 characters correctly. I leave that to you.
Last edited on
Topic archived. No new replies allowed.