Skip to content

Instantly share code, notes, and snippets.

@muaddib1971
Last active August 5, 2024 20:09
Show Gist options
  • Save muaddib1971/8afef13bf97cc0350eedebbb1c168971 to your computer and use it in GitHub Desktop.
Save muaddib1971/8afef13bf97cc0350eedebbb1c168971 to your computer and use it in GitHub Desktop.
c++catchup week 3
#include <iostream>
#include <cstdlib>
int main() {
int* i;
std::cout << *i << '\n';
return EXIT_SUCCESS;
}
#include <iostream>
#include <fstream>
#include <vector>
const int NUMARGS = 2;
const int FILEARG = 1;
std::vector<int> input() {
int num;
std::vector<int> nums;
std::cout << "Please enter integers one at a time. Press ctrl-d to finish "
"entering numbers.\n";
/* while std::cin.good() == true */
while (std::cin >> num) {
nums.push_back(num);
}
return nums;
}
bool writenums(const std::string& name, const std::vector<int>& nums) {
std::ofstream out(name);
if (!out.good()) {
// failed to open file: permission denied
perror("failed to open file");
return false;
}
// || logical or
out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
for (int i = 0; std::size_t(i) < nums.size(); ++i) {
if (i > 0) {
out << ',';
}
out << nums[i];
}
}
catch (std::ios::failure& f) {
perror("failure to write to file");
out.close();
return false;
}
out.close();
return true;
}
int main(int argc, char** argv) {
if (argc != NUMARGS) {
std::cerr
<< "Error: invalid number of args. I need a filename to write to\n";
return EXIT_FAILURE;
}
std::vector<int> theints = input();
if (!writenums(argv[FILEARG], theints)) {
std::cerr << "there was an error writing to the file\n";
}
return EXIT_SUCCESS;
}
#include <iostream>
#include <fstream>
#include <vector>
const int NUMARGS = 2;
const int FILEARG = 1;
std::vector<int> input() {
int num;
std::vector<int> nums;
std::cout << "Please enter integers one at a time. Press ctrl-d to finish "
"entering numbers.\n";
/* while std::cin.good() == true */
while (std::cin >> num) {
nums.push_back(num);
}
return nums;
}
bool writenums(const std::string& name, const std::vector<int>& nums) {
std::ofstream out(name);
if (!out.good()) {
// failed to open file: permission denied
perror("failed to open file");
return false;
}
// || logical or
out.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try {
for (int i = 0; std::size_t(i) < nums.size(); ++i) {
if (i > 0) {
out << ',';
}
out << nums[i];
}
}
catch (std::ios::failure& f) {
perror("failure to write to file");
out.close();
return false;
}
out.close();
return true;
}
int main(int argc, char** argv) {
if (argc != NUMARGS) {
std::cerr
<< "Error: invalid number of args. I need a filename to write to\n";
return EXIT_FAILURE;
}
std::vector<int> theints = input();
if (!writenums(argv[FILEARG], theints)) {
std::cerr << "there was an error writing to the file\n";
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment