Though this is a fairly simple question, I am having trouble opening the file through the inputFileStream(inputFilePath). Could someone just lead me in the correct direction (I'm not here to be given answers for a school assignment)?
#include <cmath>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
const string ID_LINE = "James McMillan - CS 1336 050 - Assignment 26";
int main(int argc, char *argv[]) {
cout << ID_LINE << endl << endl;
// guard clause - invalid number of arguments
if (argc != 3) {
cout << "Usage: " << argv[0] << "<input file path> <output file path>" << endl;
return 1;
}
//extract arguments
string programPath = argv[0];
string inputFilePath = argv[1];
string outputFilePath = argv[2];
cout << "Program path: " << programPath << endl;
cout << "Input file path: " << inputFilePath << endl;
cout << "Output file path: " << outputFilePath << endl << endl;
cout << "Creating input file stream..." << endl;
ifstream inputFileStream;
cout << "Created input file stream." << endl;
cout << "Opening input file stream: " << inputFilePath << endl;
inputFileStream.open(inputFilePath);
if (!inputFileStream.is_open()) {
cout << "Unable to open input file stream: " << inputFilePath << endl;
return 1;
}
}
Your solution might come from checking if the file exists, try
//Add this at the top
#include <experimental/filesystem>
//somewhere in the body
const auto has_the_file = std::experimental::filesystem::exists(inputFilePath);
if (!has_the_file)
{
std::cout << "Oh No! Can't find" << inputFilePath << std::endl;
}
Also instead of parsing the arguments, I would manually set the paths to confirm your expectations on how to specify file paths.
Related
I'm learning to code in C++ and I'm doing some examples of file operations. There is no problem to send to file text data when it is saved as .txt file.
However I went further and experiment on csv files:
#include <iostream>
#include <string>
#include <fstream>
#include <math.h>
#include <stdio.h>
using namespace std;
int main ()
{
int num = 0;
fstream file;
string file_name;
cout << "Input file name: ";
cin>>file_name;
file.open(file_name.c_str());
if (file.fail())
{
cout << "Unable to open file - try again" << endl;
main ();
} else
{
file << "VALUE" << "\t" << "1/x" << "\t" << "sqrt" << endl;
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
file.close();
return 0;
}
}
When I'm checking the file - there is only header:
enter image description here
What should I do to write into this csv file - results of these mathematical operations?
See my comment regarding division by zero. Also do not use integers for division. Change
while (num < 200)
{
file << num << "\t" << 1/num << "\t" << sqrt(num) << endl;
num ++;
}
to
while(num < 200)
{
num++;
file << num << "\t" << 1.0 / num << "\t" << sqrt(num) << endl;
}
I have a problem with file handling. More precisely I've written a code for exercising but after a time it won't make the .txt file.
I don't know if the error is my computer or my code but I hope someone knows the answer.
It's not the final stage but the problem started here.
(This is a simple console application)
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int Counter()
{
static int taskID;
cout << taskID++ << " - ";
}
int main(int argc, char const *argv[])
{
char inputTask[256];
string outputTask;
string listAllTask = "-l";
string addNewTask = "-a";
string removeTask = "-r";
string completeTask = "-c";
if (argc == 1) {
cout << "CLI Todo application" << endl;
cout << "====================\n" << endl;
cout << "Command line arguments:" << endl;
cout << "-l Lists all the tasks" << endl;
cout << "-a Adds a new task" << endl;
cout << "-r Removes a task" << endl;
cout << "-c Completes an task" << endl;
} else if (argc == 2) {
//create an object to access the file that containing the tasks
fstream todoApp("tasks.txt", ios::ate | ios::in | ios::out);
if (todoApp.is_open()) {
if (string(argv[1]) == listAllTask){
while (!todoApp.eof()) {
todoApp.seekg(0, ios::end);
if (todoApp.tellg() == 0) {
cout << "No todos for today! :)" << endl;
} else {
getline(todoApp, outputTask);
cout << Counter << outputTask << endl;
}
}
} else if (string(argv[1]) == addNewTask) {
cout << "Enter the new todo:" << endl;
todoApp.seekg(0, ios::end);
cin.getline(inputTask, 120);
todoApp << inputTask << endl;
todoApp.close();
cout << "-- your task has been saved --" << endl;
}
} else {
cerr << "Something went wrong, please, try again." << endl;
}
//todoApp.close();
} else {
cout << "Too many arguments!!!" << endl;
}
return 0;
}
I am trying to search a specific ID/ registration from a .txt and display the corresponding info accordingly. In this case I want to display the pricing according to the corresponding registration number which should be entered.
Reading and writing files is not the issue for me. There is a lot of info on the web in regards with reading and writing, but not much on searching and displaying according to the ID/ registration.
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
char registration[10];
//Open file
in_stream.open("Fines.dat");
//Error if opening fails
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
//Open out stream file
out_stream.open("OutStandingFines.dat");
//Error if opening fails
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
in_stream.close();
}
else
{
cout <<"File is not open: " << endl;
}
/////////////My problem is from here//////////////////////////
//Enter the registration number you wish to search
cout << "Please enter registration number: " << endl;
cin >>registration;
//I must display all cost values that have the same registration number???????? I need help with this
/*
for (int i = 0; i < 10; i++)
{
if( reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
}
}
*/
in_stream.close();
out_stream.close();
system("pause");
return(0);
}
Ok, I managed to get the output. The problem I have now is to display all the values with the same registration/ ID.
For some reason only the last row in the fstream .txt gets displayed when I enter "ABC123".
The input .txt contains the following info.
ABC123 400
DEC234 340
ABC123 500
GED345 600
ABC123 240
GEE600 120
GED345 230
GEE600 470
ABC123 120
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
int main()
{
string line;
double cost;
string reg;
ifstream in_stream;
ofstream out_stream;
string registration;
in_stream.open("Fines.dat");
if (in_stream.fail())
{
cout << "Input file could not open. " << endl;
exit(1);
}
out_stream.open("OutStandingFines.dat");
if (out_stream.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
//Display original .dat file
cout <<"Original .dat File" << endl;
if(in_stream.is_open())
{
while(in_stream >> reg >> cost)
{
cout << reg <<" " << cost << '\n';
}
}
else
{
cout <<"File is not open: " << endl;
}
//Enter Registration here
cout << "Please enter registration number: " << endl;
cin >>registration;
//compare and display all registration numbers that match
cout <<"Fines: " << endl;
if(out_stream.is_open())
{
while(reg == registration)
{
cout << fixed << setw(2)<< setprecision(2) <<"R " << cost << '\n';
out_stream << fixed << setw(2)<< setprecision(2) << "R "<< cost << endl; //send back to .dat
exit(1);
}
}
else
{
cout <<"File is not open: " << endl;
}
in_stream.close();
out_stream.close();
system("pause");
return(0);
}
I am trying to use fstream but am running into problems when trying to open a file from within Visual Studio 2013. In Visual Studio, I have two resources that I have enabled to be used in the project titeld input1.txt and input2.txt . If I directly run the application from the Debug folder using File Explorer, I am able to use the ifles. If I try to run it from within Visual Studio with ctrl, neither files can be found. I believe my code is correct, but I'm not sure what changes to make to the project to have it run correctly.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const bool VERBOSE(true);
int main(){
ifstream input;
ofstream output;
string inFileName;
string outFileName;
string tempString;
// Get input file name into a string
cout << "Input file name: " << flush;
cin >> inFileName;
if (VERBOSE)
{
cout << "Input file name is " << inFileName << endl;
}
// Convert filenames to C strings and use stream.open()
input.open(inFileName.c_str());
if (input.fail())
{
cout << "File " << inFileName << " cannot be opened" << endl;
return -1;
}
// Get output file name into a string
cout << "Output file name: " << flush;
cin >> outFileName;
if (VERBOSE)
{
cout << "Output file name is " << outFileName << endl;
}
// Convert filenames to C strings and use stream.open()
// When opening output file, it will create the file if it
// does not exist, and will clobber it if it does.
output.open(outFileName.c_str());
if (output.fail())
{
cout << "File " << outFileName << " cannot be opened" << endl;
return -2;
}
// While there is more to the input file, get a word
// and copy it to the output file on its own line.
while (!input.eof())
{
input >> tempString;
if (VERBOSE)
{
cout << " Length is " << tempString.length() << " for " << flush;
}
if (tempString.length() > 0)
{
if (VERBOSE)
{
cout << tempString << endl;
}
output << tempString << endl;
}
else
{
if (VERBOSE)
{
cout << "No more input" << endl;
}
}
// This is needed to keep the last non-whitespace word
// read in from being printed twice if the file ends in
// whitespace, including a newline.
tempString.clear();
}
cout << endl;
return 0;
}
Specify the full path to the files when you cin them.
I'm fairly new to C++ and I'm getting the following error 'fw' is not a class or namespace in the main file when I try to call the create_event_file() function.
Here is my code.
#ifndef FILE_WRITER_H
#define FILE_WRITER_H
#include <string>
using namespace std;
class File_Writer{
private:
int test;
public:
File_Writer() { }
void create_event_file(void);
void write(const string file_name, string data);
};
#endif // FILE_WRITER_H
The cpp file
#include "file_writer.h"
#include <iostream>
#include <fstream>
using namespace std;
File_Writer::File_Writer(void){
cout << "Object of File_Writer is created" << endl;
}
void File_Writer::create_event_file(void){
ofstream outputFile;
outputFile.open("event.txt");
string data;
cout << "Enter event title : " << endl;
getline(cin,data);
outputFile << textToSave;
cout << "Enter event date : " << endl;
getline(cin,data);
outputFile << textToSave;
cout << "Enter event start time : " << endl;
getline(cin,data);
outputFile << textToSave;
outputFile.close();
}
void File_Writer::write(const string file_name, string data){
ofstream outputFile;
outputFile.open("all.txt");
outputFile << data;
outputFile.close();
}
And the main file
#include <iostream>
#include "file_writer.h"
using namespace std;
int main(){
string input;
File_Writer fw;
cout << "Welcome to the event creation program!\n" << endl;
cout << "---------------------------" << endl;
cout << "| event - To create event file |" << endl;
cout << "| entrants - To create entrants file |" << endl;
cout << "| coursess - To create courses file |" << endl;
cout << "---------------------------\n" << endl;
getline(cin,input);
if(input == "event")
fw::create_event_file();
}
Thanks in advance
Replace this, which implies that fw is the name of a class or namespace:
fw::create_event_file();
// ^^ This is a "scope opearator"
With this, which implies that fw is a variable:
fw.create_event_file();
// ^ This is a "member access opearator"