Ask Your Question
3

How can integers be organized into three columns from a text file using C++?

asked 2023-06-09 04:12:02 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-06-09 04:16:01 +0000

devzero gravatar image

Here's a sample solution that reads integers from a text file and organizes them into three columns before outputting them to the console:

#include <iostream>
#include <fstream>

using namespace std;

int main() {
    ifstream inputFile("input.txt"); // Open the input file

    if (!inputFile.is_open()) {
        cout << "Failed to open input file." << endl;
        return 1;
    }

    int integer; // Variable to store the input integers
    int lineCount = 0; // Counter to keep track of the number of integers read
    while (inputFile >> integer) { // Read integers from file until end of file is reached
        if (lineCount % 3 == 0) { // If this is the first integer in the line, start a new line
            cout << endl;
        }
        cout << integer << "\t"; // Output the integer followed by a tab
        lineCount++; // Increment the line count
    }

    cout << endl; // Output a final newline character

    inputFile.close(); // Close the input file

    return 0;
}

In this solution, we first declare an ifstream object called inputFile to handle the input file. We then attempt to open the file using the .is_open() method of the ifstream class. If the file fails to open, we output an error message and return a non-zero exit code to indicate failure.

Within the main loop of the program, we read integers from the file using the input operator >>. For every integer we read, we check whether it is the first integer in a line (using the modulus operator %). If it is, we output a newline character to start a new line of output. We then output the integer itself followed by a tab character (\t) to separate the columns. We also increment the lineCount variable at the end of each iteration of the loop.

We close the input file at the end of the program and output a final newline character.

Assuming the input file contains the following integers:

1 2 3 4 5 6 7 8 9 10 11

The program's output would be:

1   2   3   
4   5   6   
7   8   9   
10  11  
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-09 04:12:02 +0000

Seen: 15 times

Last updated: Jun 09 '23