1 | initial version |
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