-
Homepage
-
Parsing And File I/O Homework Help in C++
Writing A Program That Takes an Output File of a Specified Format in C++
Question: Write a C++ program that takes an expected output file named "input.txt" of the exact format;
(int), (int), (int)
(string)
(int), (int), (int)
(string)
(int), (int), (int)
(string)
(int), (int), (int)
(string)
(int), (int), (int)
(string)
Solution.
1,2,3
ham
1,1,1
let
Writing A Program That Sums the ints Of the Program in C++
Question: The program should then sum the ints of each line and output the immediately following line's sting, that many times, separated by comma so that;
123
ham
becomes:
ham, ham, ham, ham, ham, ham
Note: you may also add trailing commas at the end of the line if it's easier for you.
Your final output format should not be the console. Instead, your program should open a second file and write your output in a file named "output.txt" which should be five lines of comma-separated words.
Solution.
#include
#include
#include
#include
// Entry point of the program
int main()
{
// Open and process the input file
std::ifstream inFile("input.txt");
std::ofstream outFile("output.txt");
if (!inFile.is_open())
{
std::cout << "Error: Failed to open input.txt\n";
return 0;
}
if (!outFile.is_open())
{
std::cout << "Error: Failed to open output.txt\n";
return 0;
}
// Process each line in the file
std::string line;
while (getline(inFile, line))
{
std::stringstream ss(line);
// Extract 3 ints and sum them up
int total = 0;
std::string token;
while (getline(ss, token, ','))
{
std::stringstream ssInt(token);
int value;
ssInt >> value;
total += value;
}
// Print the next string in file based on total
getline(inFile, line);
for (int i = 0; i < total; i++)
{
outFile << line;
if (i + 1 < total)
outFile << ",";
}
outFile << "\n";
}
inFile.close();
outFile.close();
std::cout << "Processing complete.\n";
std::cout << "Output written to output.txt file.\n";
return 0;
}