Trouble with the correct format of displaying text string from the file in C++

70 Views Asked by At

I have a problem with the correct formatting of text (a string of numbers), after retrieving it from a file. My goal is to display it in the console format:

number number number number ... number

but it displays in form, where each of the number is displayed in a separate line e.g.:

6
928
81
4
496
3
8
922
0
5
39
731
53

The desired format:

6 928 81 4 496 3 8
922 0 5 39 731 53

etc.

Example Input File (start.txt) looks as follows :

6 928 81 4 496 3 8
922 0 5 39 731 53
6 3 48 9 15 971 48
631 30 7 04 31 96
18 78 409 30 55 6
0 75 8 4 0 9 73 61 3
8 36 40 21 05 825
66 4 7 9 05 96 3
6 43 5 3 39 3 07
77 0 2 76 7 8 3 5

The code:

#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>  
#include <random>
#include <chrono> 
#include <cmath> 
#include <string>
#include <string.h>

using namespace std;

int main(int argc, char* argv[])
{

    {
        const string OSOBNIKI{ "start.txt" };

        ifstream file(OSOBNIKI);
        if (file)
        {
            string chromosom;

            while (file>> chromosom)
                cout << chromosom << endl;
        }
    }
    return 0;
}

I have been trying it with multiple cout's. But I have not found the right solution to format it as in original file. It would be best to use some kind of loop as I guess.

1

There are 1 best solutions below

0
Remy Lebeau On

Printing std::endl writes a new line to the output. That is why each number is being printed out on its own line.

You want to print a new line only when you encounter a new line in the input, but operator>> ignores leading whitespace, including new lines. So, your current code has no way to know when a new line is encountered.

To do what you want, use std::getline() to read the file line-by-line, and use std::istringstream to read the numbers from each line.

For example:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

int main(int argc, char* argv[])
{
    const string OSOBNIKI{ "start.txt" };

    ifstream file(OSOBNIKI);
    string line;
    int chromosom;

    while (getline(file, line)) {
        istringstream iss(line);
        while (iss >> chromosom) {
            cout << chromosom << ' ';
        }
        cout << endl;
    }

    return 0;
}