char uname[30], psw[20],fname[3],bname[30],pnumber[30];
int x,pil;
void createAcc() {
ofstream f("data/"+ uname + ".txt"); //i want the file to be saved into data/uname.txt
// ex: the user is input is myfile
// so it will be saved into data/myfile.txt
if(f.is_open()){
f<<"Nama Depan : "<<fname<<endl;
f<<"Username : "<<uname<<endl;
f<<"Password : "<<psw<<endl;
f<<"Nama Belakang : "<<bname<<endl;
f<<"Nomor Telepon : "<<pnumber<<endl;
f.close();
}
else cout<<"error: cannot write into file"<<endl;
}
Asked
Active
Viewed 56 times
0
-
2Don't use arrays of `char` to represent strings (and keep in mind that a string literal (like `"data/"`) is represented as a nul-terminated array of `char`). Use `std::string` instead - it is an object that represents a string and allows operations that are not possible (directly) with arrays. In particular, arrays of `char` cannot be appended to each other using addition (`+`) like you are doing. `std::string`s CAN be appended using `+` - both to each other and (with care) to nul-terminated arrays of `char` (including string literals) and can also be initialised using string literals. – Peter Apr 21 '22 at 09:11
-
Does this answer your question? [How to concatenate multiple C-style strings in C++?](https://stackoverflow.com/questions/64478222/how-to-concatenate-multiple-c-style-strings-in-c) – wovano Apr 21 '22 at 09:55
-
Yes, you can user input to name a file. However, you probably want to define the file name *after* you get the name from the user and not attempt to do so before. – lurker Apr 21 '22 at 10:30