what should i change so my file will show up? - c++

I starting over a c++ journey and I cannot upload a file and parse it. Could you please tell me what is wrong with my code?
thank you
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, const char * argv[]) {
std::string FileName("upload.txt");
std::ifstream MyFile(FileName);
MyFile.open(FileName);
std::string LastName;
std::string Name;
int Number;
if (!MyFile.is_open()){
std::cout <<"The fils is not opened \n"<< std::endl;
}
std::cout<<"olivier"<< std::endl;
while (MyFile >> LastName >> Name >> Number){
std::cout<<"olivier"<< std::endl;
std::cout<< LastName << std::endl;
}
return 0;
}

You are opening the file twice
std::ifstream MyFile(FileName);
MyFile.open(FileName);
First time you use constructor and then you are trying to open the same file. Just remove the MyFile.open(FileName); and everything will be fine.

Related

C++ Read and append

Hello everyone I need help with one of the excercise I am doing. I have searched alot but didn't found what I was looking.
So, I want my program to read from one .txt file and then gives output in another .txt file.
Source File have this contents.
Name Salary
Aamir 12000
Amara 15000
Adnan 13000
Afzal 11500
Output File should have this
Name Salary
Aamir 14000
Amara 17000
Adnan 15000
Afzal 13500
The program should read the source file and add 2000 to the salary in the output file.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char c;
char inputFile[] = "my-file.txt";
char outputFile[] = "my-file-out.txt";
ifstream inFile;
ofstream outFile;
inFile.open(inputFile, ios::in);
if (!inFile)
{
cout << "The file cannnot be open please check" << endl;
exit(1);
}
outFile.open(outputFile, ios::out | ios::ate);
while ((c = inFile.get()) != EOF)
{
outFile.put(c);
}
inFile.close();
outFile.close();
}
I was able to copy the content from source file to output file after some struggle but now no matter what I do it won't give me the desirable solution. What should I add into the code that would give the correct output.
prefer using const std::string over const char*
extract the first line and write to output stream. std::getline can help you.
read data from source with operator>> if your source data constists of fixed types of datas.
raise salary and write to dest file with operator<<
Following code works but I omitted handling exceptions or erros for simplicity. You should add handling code when opening, reading, writing data and closing streams.
#include <fstream>
#include <iostream>
#include <string>
using std::string;
int main() {
const string name_input_file = "D:/my-file.txt";
std::ifstream ifs(name_input_file);
const string name_output_file = "D:/my-file-out.txt";
std::ofstream ofs(name_output_file);
string fist_line;
std::getline(ifs, fist_line);
ofs << fist_line << '\n';
string name;
int salary;
while (ifs && ofs) {
ifs >> name >> salary;
salary += 2'000;
ofs << name << ' ' << salary << '\n';
}
return 0;
}
Here's a dirty solution. Reads my-file.text, adds 2000 to each salaries and writes the new strings to my-file-out.txt. Note that my-file-out.txt will lose its previous data everytime you run the program.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <string>
int main()
{
std::ifstream ifile;
std::ofstream ofile;
ifile.open("my-file.txt", std::ifstream::in);
ofile.open("my-file-out.txt", std::ofstream::out | std::ofstream::trunc);
std::string line{};
bool flag{true};
while (std::getline(ifile, line))
{
if (flag){ flag = false; ofile << line << "\n"; continue; }
std::string salary{};
for (size_t i{line.length() - 1}; i >= 0; --i)
{
if (line[i] == ' ') break;
salary += line[i];
}
std::reverse(salary.begin(), salary.end());
line.replace(line.length() - salary.length(), line.length(), std::to_string(std::stoi(salary) + 2000));
ofile << line << "\n";
}
ifile.close();
ofile.close();
}

Naming an output file from a user entered string

This is my first project in C++. I took a course using C previously and file I/O seems to differ a little.
The project requires the user to enter a name for saving the output file.
I know I should use ofstream which should look like this:
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
I've bolded the snippet that's causing confusion.
How can I name the file from a string entered by the user?
*Note, C type string, so an array of characters.
#include < string > is not allowed
As my other answer has got a negative vote, here's another solution without #include <string>
You can just save the input from the user in a temporary char array and then save it to a string variable std::string.
Includes that are necessary:
#include <iostream>
#include <fstream>
Saving an input from an user into a char array:
char input[260];
cin >> input;
To then save it in a string variable just do this:
string filename = input;
To open a file stream you'll need to use std::ofstream. Please keep in mind, that the file is created in the same folder as the project/application is.
std::ofstream outfile (filename + "." + "file extension");
And as you already know this outfile.open(); opens the file.
With outfile << "hello"; you can write into the file.
To close the file, use outfile.close(); to close the file.
Here you have a little example code:
#include <iostream>
#include <fstream>
using namespace std;
void main()
{
char input[260];
cin >> input;
string filename = input;
ofstream outfile(filename + "." + "txt");
outfile << "hello";
outfile.close();
}
I hope this helps.
Regards.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string path;
string name;
string h_path;
string text;
void create() {
ofstream file(h_path, ios::app);
if (!file.fail()) {
file << text;
file.close();
}
}
int main() {
cout << "please enter path(c:\\folder\): ";
cin >> path;
cin.ignore();
path = path + "/";
cout << "please enter the name of the file (test.txt): ";
getline(cin, name);
cout << "content of the file: ";
getline(cin, text);
h_path = path + name;
create();
cout << "new file created";
cout << h_path;
}
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string fileName;
cin >> fileName;
ofstream myfile;
myfile.open(fileName);
myfile << "Writing this to a file.\n";
myfile.close();
}

Reading from input file and storing in array c++

I want to read from a file.txt that looks like this:
process_id run_time
T1 23
T2 75
Read each line and store integers of run time (tab separation)in an array
My problem now is to read the content of the file .. and how to get the integer after the tab separation?
thanks
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
int process_id[100];
int run_time[100];
int arrival_time[100];
char quantum[50];
int switching;
char filename[50];
ifstream ManageFile; //object to open,read,write files
cout<< "Please enter your input file";
cin.getline(filename, 50);
ManageFile.open(filename); //open file using our file object
if(! ManageFile.is_open())
{
cout<< "File does not exist! Please enter a valid path";
cin.getline(filename, 50);
ManageFile.open(filename);
}
while (!ManageFile.eof())
{
ManageFile>>quantum;
cout << quantum;
}
//ManageFile.close();
return 0;
}
use C++, not C
don't use std::cin.getline, use std::getline (it works with std::string and is safer)
use a vector instead of hard-dimensioned arrays
use a vector of struct instead of "corresponding arrays"
don't use while (!stream.eof())
Here's a sample that might be helpful:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;
struct Record {
int process_id;
int run_time;
int arrival_time;
};
int main() {
std::vector<Record> records;
int switching;
std::string filename;
ifstream infile;
while (!infile.is_open()) {
cout << "Please enter your input file: ";
std::getline(std::cin, filename);
infile.open(filename); // open file using our file object
cout << "File cannot be opened.\n";
}
std::string quantum;
std::getline (infile, quantum); // skip header row
while (std::getline(infile, quantum)) {
// e.g.
Record current;
std::istringstream iss(quantum);
if (iss >> current.process_id >> current.run_time >> current.arrival_time)
records.push_back(current);
else
std::cout << "Invalid line ignored: '" << quantum << "'\n";
}
}
You can try something like this:
while (!ManageFile.eof())
{
quantum[0] = 0;
ManageFile>>quantum;
if (strcmp(quantum, "0") == 0 || atoi(quantum) != 0)
cout << quantum << endl;
}
Of course, you need to include in the head
Use function ignore from istream [http://www.cplusplus.com/reference/istream/istream/ignore/]
while (!ManageFile.eof())
{
std::string process_id;
int run_time;
ManageFile >> process_id;
ManageFile.ignore (256, '\t');
ManageFile >> run_time;
}
Using fscanf instead of ifstream can make the job a lot easier.
char str[100];
int n;
....
fscanf(FILE * stream,"%s %d", str, &n);
You will get the string in str and integer in n.

C++ Displaying a Text File...("Echo" a Text File)

So I'm really stuck trying to figured this bug on the program that is preventing me from displaying the text of my program..
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <string>
#include <stdio.h>
using namespace std;
int main ()
{
ifstream infile;
ofstream offile;
char text[1024];
cout <<"Please enter the name of the file: \n";
cin >> text;
infile.open(text);
string scores; // this lines...
getline(infile, scores, '\0'); // is what I'm using...
cout << scores << endl; // to display the file...
string name1;
int name2;
string name3;
int name4;
infile >> name1;
infile >> name2;
infile >> name3;
infile >> name4;
cout << "these two individual with their age add are" << name2 + name4 <<endl;
// 23 + 27
//the result I get is a bunch of numbers...
return 0;
}
Is there any way cleaner or simple method i can used to display the file ?
All the method in the internet are difficult to understand or keep track due to
the file is open in loop..
I want a program that you type the name of the file and displays the file
the file will contain the following...
jack 23
smith 27
Also I need to obtain data from the file now I'm using the above code to obtain that information from the file...
loop is probably the best thing you can do.
so if you know the format you could simply do it like this
#include <iostream>
#include <fstream>
using namespace std;
int printParsedFile(string fileName) { // declaration of a function that reads from file passed as argument
fstream f; // file stream
f.open(fileName.c_str(), ios_base::in); // open file for reading
if (f.good()) { // check if the file can be read
string tmp; // temp variable we will use for getting chunked data
while(!f.eof()) { // read data until the end of file is reached
f >> tmp; // get first chunk of data
cout << tmp << "\t"; // and print it to the console
f >> tmp; // get another chunk
cout << tmp << endl; // and print it as well
} else {
return -1; // failed to open the file
}
return 0; // file opened and read successfully
}
you can call then this function for example in your main() function to read and display file passed as argument
int main(int argc, char** argv) {
string file;
cout << "enter name of the file to read from: "
cin >> file;
printParsedFile(file);
return 0;
}
I personally use stringstreams for reading one line at a time and parsing it:
For example:
#include <fstream>
#include <stringstream>
#include <string>
std::string filename;
// Get name of your file
std::cout << "Enter the name of your file ";
std::cin >> filename;
// Open it
std::ifstream infs( filename );
std::string line;
getline( infs, line );
while( infs.good() ) {
std::istringstream lineStream( line );
std::string name;
int age;
lineStream >> name >> age;
std::cout << "Name = " << name << " age = " << age << std::endl;
getline( infs, line );
}

How to create ofstream file with name of variable?

char NAME[256];
cin.getline (NAME,256);
ofstream fout("NAME.txt"); //NAME???????
What i need to do to create file with NAME name?
You could try:
#include <string>
#include <iostream>
#include <fstream>
int main() {
// use a dynamic sized buffer, like std::string
std::string filename;
std::getline(std::cin, filename);
// open file,
// and define the openmode to output and truncate file if it exists before
std::ofstream fout(filename.c_str(), std::ios::out | std::ios::trunc);
// try to write
if (fout) fout << "Hello World!\n";
else std::cout << "failed to open file\n";
}
Some useful references:
http://en.cppreference.com/w/cpp/string/basic_string
http://en.cppreference.com/w/cpp/string/basic_string/getline
http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream
http://en.cppreference.com/w/cpp/io/basic_filebuf/open
http://en.cppreference.com/w/cpp/io/ios_base/openmode
Like this:
#include <string>
#include <fstream>
std::string filename;
std::getline(std::cin, filename);
std::ofstream fout(filename);
In older versions of C++ the last line needs to be:
std::ofstream fout(filename.c_str());
You can try this.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string fileName;
cout << "Give a name to your file: ";
cin >> fileName;
fileName += ".txt"; // important to create .txt file.
ofstream createFile;
createFile.open(fileName.c_str(), ios::app);
createFile << "This will give you a new file with a name that user input." << endl;
return 0;
}