User Input to a File
Write a program that prompts the user to enter some text. The program should then write the user's input to a file named input.txt. If the file already exists, the program should overwrite its contents with the new input.
Hint
- Use
<fstream>to handle file operations. - Use the
std::ofstreamclass to create and write to the file.
Answer
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::string userInput;
std::cout << "Enter some text: ";
std::getline(std::cin, userInput);
// Open the file (this will overwrite any existing content)
std::ofstream outFile("input.txt");
if (outFile) {
outFile << userInput; // Write user input to the file
std::cout << "Input saved to input.txt." << std::endl;
} else {
std::cerr << "Failed to open input.txt for writing." << std::endl;
}
// File is closed automatically when ofstream goes out of scope
return 0;
}