How to use a variable as a files name? - c++

I've been working on a program that creates and stores information onto files. My only problem that is keeping me from going any farther is the files name. I can manually name the file but I can't use a variable (any would do: number, character anything) for the files name, and for the contents of the file. Here's the 4 lines of code that have driven me up walls for a while now:
ofstream file;
file.open ("txt.txt"); \\I can manually create names, but that's not what I'm after
file.write >> fill; \\I attempted to use a 'char' for this but it gives errors based on the "<<"
file.close();
This is my first time using this site. Sorry in advance.

You may use variables of type strings and ask the user for keyboard input to name your file and fill in contents.
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char** argv) {
string fileName;
string contents;
cout << "What would you like the file name be? : ";
cin >> fileName;
cout << "\nPlease write the contents of the file: ";
cin >> contents;
ofstream file;
file.open(fileName.c_str()); // provide the string input as the file name
if(file.is_open()){ // always check if the program sucessfully opened the file
file << contents << endl; // write the contents into the file
file.close(); // always close the file!
}
return 0;
}
Note that this program will read input from user for contents until it reaches a newline character '\n' or white space ' '. So if you write HELLO WORLD! as the input for contents, it will only read HELLO.
I'll leave how to read the entire line including whitespaces as exercise for you. I also suggest you grab a C++ book and study file input/output.

It really depends? C++11 or C++03?
First create a string:
std::string fname = "test.txt";
In C++11, you can just do:
file.open(fname);
However in C++03, you must:
file.open(fname.c_str());

Related

.write() not working in file handling c++ [duplicate]

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.
The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.
ofstream write;
std::string studentName, roll, studentPassword, filename;
public:
void studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
filename = roll + ".txt";
write.open(filename.c_str(), ios::out | ios::binary);
write.put(ch);
write.seekp(3, ios::beg);
write.write((char *)&studentPassword, sizeof(std::string));
write.close();`
}
You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()
If you have fmt available:
#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...
But you are not really writing a password to a file, right?

Reading binary files and fill vector c++ [duplicate]

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.
The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.
ofstream write;
std::string studentName, roll, studentPassword, filename;
public:
void studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
filename = roll + ".txt";
write.open(filename.c_str(), ios::out | ios::binary);
write.put(ch);
write.seekp(3, ios::beg);
write.write((char *)&studentPassword, sizeof(std::string));
write.close();`
}
You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()
If you have fmt available:
#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...
But you are not really writing a password to a file, right?

.size() string manipulation not reading actual length/size of characters c++

I am trying to read in an essay from a file which I then need to change each beginning letter of a sentence to an upper case letter and then send the corrected essay back to a file called correct.txt. The essay is stored in essay.txt.
So far I am just working with understanding the conversions from files to string in order for me to proceed with the rest of the question. So far, I have a string variable which which holds the essay with the words separated by a single space. I noticed that when I was trying to work with the size of my new string, it was not giving me the correct answer and I cannot figure out why. If you have any suggestions on how I can get it to notice the correct amount of characters, I would really appreciate it.
One more question while you're here, I know that moving forward, in order to change the beginning letters of the sentence to upper case, I need to first find the periods. Once I have this position, I can use pos+2 (including the preceding whitespace after the period) for the character that needs to become upper case. Is this the correct way of going about this and do you have any other tips on how to go forward with this?
Here is my code so far:
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
//declaring variables and creating objects
ifstream inputFile;
ofstream outputFile;
char inputFileName[20], outFileName[20];
cout << "Enter name of the file you want to open: " << endl;
cin >> inputFileName;
inputFile.open(inputFileName);
if (inputFile.fail()) {
cout << "Input file opening failed.\n";
exit(1);
}
cout << "Enter name of the file you want to send the output to: " << endl;
cin >> outFileName;
outputFile.open(outFileName);
if (outputFile.fail()) {
cout << "Output file opening failed.\n";
exit(1);
}
//while the file is open, it sends the contents to the string variable "essay"
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
//this is to check for the correct size of the string "essay" before moving on to the rest of the code
int size = essay.size();
cout << size << endl;
return 0;
}
Your understanding of how the input stream works is incorrect.
The core of your code is this loop:
string essay;
inputFile >> essay;
while (!inputFile.eof()) {
cout << essay << " ";
inputFile >> essay;
}
What this does is that it reads the first word into essay, then, as long as the eof marker is not set on the stream it echoes back the word just read, and then reads another word, overwriting the previous one.
Here's the correct code. Note that checking for eof in a loop condition is a bad idea, because it doesn't quite do what you want, and would also get you stuck in an infinite loop if the stream instead entered an error condition.
string word;
while (inputFile >> word) { // read a word and stop if this fails for any reason
essay += word;
essay += " ";
}
Though I'm not sure why you read the file word by word instead of all at once.
Also, I feel the need to repeat what M.M. said in a comment: your use of raw character arrays on input is unsafe and unnecessary. Just use string. You need to then write inputFile.open(inputFileName.c_str()) unless your standard library is new enough to have the string overloads of these functions, but that is fine. The other way of doing it is dangerous and a very bad habit to get into.
Try include cstring on top of string as well.
String is considered char array which is a more 'unique' way of storing data. You can try the code listed below.
int size = essay.length();

Output text C++

How may I add a none fixed text to a .txt file? So that I can add text that I just added by hand to the file.
#include <iostream>
#include <fstream>
using namespace std;
int main () {
int x;
ofstream myfile;
myfile.open ("teksts.txt", ios::app);
myfile << x;
myfile.close();
return 0;
}
Also after the file has added the text to the .txt document, how can I pause the run window so It would say "The file has been updated!" and only after I press enter it would exit?
You cannot write a variable to a file, and then replace it later, just like you can't write a variable to cout, and then replace it later.
If you're looking to open a file, write something to it, and then reopen it later, you'll need to use a unique string of text, and then replace that.
myfile << "ABC %%UNIQUE_STRING%% DEF";
Then later...
string uniqueValue = "%%UNIQUE_STRING%%";
string stringObject;
getline(myfile, stringObject);
stringObject.replace(stringObject.find(uniqueValue), uniqueValue.length(), "New Value");
If you're looking for something automatic, everytime the program runs, (since the above will only work once), you'll have to be more clever. One potential option would be to always write to the same character index, and the same amount of characters.
You need to give x a value before you send it to the file ( currently you are just sending junk value)
myfile.open ("teksts.txt", ios::app);
cout << "Please enter text to write to file: ";
cin >> x;
myfile << x;
Just add a statement like cout<< "The file has been updated!";.
To view the output use getchar();
If you want to overwrite the contents each time you open the file, open it in ios::out mode instead. Currently you are using ios::app.
I would also advise to change x into a string, that way you will be able to save text to it.

How to write std::string to file?

I want to write a std::string variable I am accepting from the user to a file. I tried using the write() method and it writes to the file. But when I open the file I see boxes instead of the string.
The string is only a variable length single word. Is std::string suitable for this or should I use a character array or something.
ofstream write;
std::string studentName, roll, studentPassword, filename;
public:
void studentRegister()
{
cout<<"Enter roll number"<<endl;
cin>>roll;
cout<<"Enter your name"<<endl;
cin>>studentName;
cout<<"Enter password"<<endl;
cin>>studentPassword;
filename = roll + ".txt";
write.open(filename.c_str(), ios::out | ios::binary);
write.put(ch);
write.seekp(3, ios::beg);
write.write((char *)&studentPassword, sizeof(std::string));
write.close();`
}
You're currently writing the binary data in the string-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream, an "out-file-stream". It behaves exactly like std::cout, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close() isn't strictly neccessary here: the deconstructor of ofstream can handle this for us as soon as out goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str(). So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
Assuming you're using a std::ofstream to write to file, the following snippet will write a std::string to file in human readable form:
std::ofstream file("filename");
std::string my_string = "Hello text in file\n";
file << my_string;
remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()
If you have fmt available:
#include <fmt/os.h>
// ...
fmt::output_file(filename).print("{}\0\0{}", ch, studentPassword);
// ...
But you are not really writing a password to a file, right?