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
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
Asked: 2023-06-09 04:12:02 +0000
Seen: 15 times
Last updated: Jun 09 '23
What does an empty name signify in the inotify_event structure in the C++ language?
What is the method to get a printable output of a C++11 time_point?
What are the differences between TREEFROG, CROW, and the CPPCMS C++ framework?
How can the NTP flag be set for Linux time in C++?
What is the process of redefining a c++ macro with fewer parameters?
What are some other options instead of Scipy to compute CubicSpline?
How can a list be sorted alphabetically within a console application?