Skip to content

Instantly share code, notes, and snippets.

@mshafae
Last active October 30, 2024 06:25
Show Gist options
  • Save mshafae/30ad98e4ca6f0aa45db9e9a31c5625af to your computer and use it in GitHub Desktop.
Save mshafae/30ad98e4ca6f0aa45db9e9a31c5625af to your computer and use it in GitHub Desktop.
CPSC 120 Read a line of text from cin and then write the line out to a file
// Gist https://gist.github.com/30ad98e4ca6f0aa45db9e9a31c5625af
// Filename cpsc120_write_message.cc
// CompileCommand clang++ -std=c++17 cpsc120_write_message.cc
// Read a line of text from cin and then write the line out to a file
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(int argc, char const *argv[]) {
std::vector<std::string> args{argv, argv + argc};
if (args.size() < 2) {
std::cout << "Please provide a path to a file.\n";
return 1;
}
std::string output_file_name{args.at(1)};
std::ofstream output_file_stream{output_file_name};
if (!output_file_stream.is_open()) {
std::cout << "Could not open the file " << output_file_name << "\n";
return 1;
}
std::string message;
std::cout
<< "Type your message out and when you're done press return or enter.\n";
std::getline(std::cin, message, '\n');
output_file_stream << message << "\n";
if (output_file_stream.bad()) {
std::cout << "I/O error\n";
return 1;
} else if (output_file_stream.fail()) {
std::cout << "Encountered something crazy! Long line?\n";
return 1;
}
std::cout << "Your message was saved into " << output_file_name << ".\n";
// When you open something, close it!
// This is a very important habit to develop.
output_file_stream.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment