Following is the code to have output file. What if I want to give this output file different name each time, i.e., as demanded by the user. What kind of getline command would help.
I know I can simply cin a string name my_file but the desired name is in the input not in the string name.
void save(cdStruct *ptr) //Function that saves database info to file
{
ofstream dataFile;
dataFile.open("output.txt", ios::out | ios::app);
dataFile << ptr->title << endl;
dataFile << ptr->artist << endl;
dataFile << ptr->numberOfSongs << endl;
dataFile << ptr->number << endl;
dataFile.close();
}
You want to change this line:
dataFile.open("output.txt", ios::out | ios::app);
To something like this??
dataFile.open(my_name_string, ios::out | ios::app);
If yes, you have only to read this string before, add ".txt" and it's everything.
Check this code:
string name;
cin >name;
name.append(".txt");
ofstream dataFile;
dataFile.open(name.c_str(), ios::out | ios::app);
dataFile.close();
From your comments on other answers it sounds like you are passing the file name as a std::string to std::ofstream::open. Before C++11 it only accepted a const char * parameter, not a std::string (see this reference).
To fix this use filename.c_str() as the first parameter instead of filename. This returns a null-terminated char array, the type expected by std::ofstream::open
Your error message tells the following: you are using std::string at some point when you should be using char const *. Now we only need to find the proper place where the error occurs.
A quick look into online documentation of std::getline tells us, that this function is not the problem: the signature allows std::string. The only other thing that has changed is the std::ofstream(filename, std::ios::out | std::ios::ate), so we check the documentation of std::ofstream; indeed a char const *.
This problem should be quickly solved by replacing
std::ofstream dataFile(filename, std::ios::out | std::ios::ate);
with
std::ofstream dataFile(filename.data(), std::ios::out | std::ios::ate);
and then it should compile.
It is very important that you try to understand the error messages that your compiler is giving you and search for references where the problem may lie.
Your specific problem is not "Give output file desired name as desired by the user", but "How to read user input in command line program". For this, you can use std::getline:
#include <iostream>
#include <string>
int main() {
std::string filename;
getline(std::cin, filename);
}
One could be tempted to use the operator<< overloads,
#include <iostream>
#include <string>
int main () {
std::string filename;
std::cin >> filename;
}
however, they would give wrong results if your filename contains whitespace characters.
Sidenote: Don't pass nullable pointers when you want to enforce non-null values:
// don't: void save(cdStruct *ptr)
void save(cdStruct const &ptr) // <- ah, better
Related
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?
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?
I write to a file but when I try to read from the file I get an infinite loop
When I work with a regular file I can print this shape but with no binary file. why?
And when I want to do actions on a sample binary file how do I do this if I can not go over the file with a loop?
I would be happy to explain thank you.
main.cpp:
string text;
//getline(cin, text);
text = "3.14159#12#Good Luck!# - 2.718";
char ch2;
fstream outBinary1;// output to text
outBinary1.open("binary1.txt", ios::binary | ios::out);
const char *temp = text.c_str();
outBinary1.write(temp, text.length());
outBinary1.get(ch2);// first char in text
while (!outBinary1.eof()){
cout << ch2 ;
outBinary1.get(ch2);
}
outBinary1.close();
Unfortunately it is hard to understand what you want to establish and have problems with, but I will give it a try.
If you want to read from the file you have to specify ios::inadditionally.
Supposed you want to read from the beginning of the file (after writing), you have to reposition the stream first (according to this). Therefore seekg can be used.
What you want may look like that:
string text;
//getline(cin, text);
text = "3.14159#12#Good Luck!# - 2.718";
char ch2;
// You may want to rename this
fstream outBinary1;// output to text
outBinary1.open("binary1.txt", ios::binary | ios::out | ios::in);
const char *temp = text.c_str();
outBinary1.write(temp, text.length());
outBinary1.seekg(0, outBinary1.beg); // only if you want to read from the beginning
outBinary1.get(ch2);// first char in text
while (!outBinary1.eof()){
cout << ch2 ;
outBinary1.get(ch2);
}
outBinary1.close();
#include <fstream>
#include <iostream>
using namespace std;
void f(){
const string text("3.14159#12#Good Luck!# - 2.718");
fstream outBinary1;
outBinary1.open("binary1.txt", fstream::in | fstream::out | fstream::trunc);
outBinary1.write(text.c_str(), text.length());
outBinary1.seekg (0, outBinary1.beg);
char ch2;
outBinary1.get(ch2);// first char in text
while (outBinary1){
cout << ch2 ;
outBinary1.get(ch2);
}
outBinary1.close();
}
int main(int, char**){
f();
return 0;
}
The two lines to change are
outBinary1.open("binary1.txt", fstream::in | fstream::out | fstream::trunc);
outBinary1.seekg (0, outBinary1.beg);
The first one to force the file to be created and the second one to move the fp back to start. Compiled with g++ and no switches
For instance, I want a file to be created using the myfile.open that has the title "m[name]f", with [name] being a string inputted by the user. I know how to collect strings, but how do I make it a part IN THE MIDDLE of the file name?
In BASIC, I would use:
open "m";namestring$;"f.txt"
How would I do this in C++?
Edit: Unfamiliar with the term "string concatenation" at the time.
std::string filename = "m";
filename += namestring;
filename += "f.txt";
std::ifstream my_file(filename.c_str());
The std::string is the C++ string type. The += operator is concatenation. I'm assuming that namestring is another std::string variable.
Below code will work .
#include <fstream> // std::ofstream
#include<iostream>
#include<string>
int main () {
std::string str;
std::cin>>str;//take input from user (can also use getline if input contain white space)
std::ofstream ofs;//you may use other I/O
ofs.open ((std::string(str+".txt")).c_str(), std::ofstream::out | std::ofstream::app);
ofs << " more lorem ipsum";
ofs.close();
return 0;
}
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?