How do I create a text file with the name of a string that was input by the user?
How do I create a text file with the name of a string that was input by the user?
Code:#include <fstream.h> #include <iostream.h> int main() { char str[30]; cin>>str; ofstream a_file(str); //Whatnot... return 0; }
I was born; I shall die. Between those two events there is life. I don't know why, and I don't question it; I merely live.
It doesn't work.PHP Code:
#include <fstream.h>
#include <iostream.h>
int main()
{
char str[30];
cin>>str;
char str2[34];
for (int i = 0; i<=30; i++)
{
str2[i]=str[i];
}
str2[31]='.';
str2[32]='t';
str2[33]='x';
str2[34]='t';
//took str, copied it, added .txt (called str2)
ofstream a_file(str2);
a_file << "sadfasf";
return 0;
}
Code:char str[30]; cin>>str; strcat(str,".txt"); ofstream a_file(str); a_file << "sadfasf";
Of course it doesn't work. Try:
ofstream f;
f.open (.....);
Current Setup: Win 10 with Code::Blocks 17.12 (GNU GCC)
char str[30];
cin >> str;
char str2[34];
for (int i = 0; i<=30; i++)
{
str2[i]=str[i];
}
str2[31]='.';
str2[32]='t';
str2[33]='x';
str2[34]='t';
Two problems with this approach.
1) what if the user inputs only 4 char instead of thirty. Say the input is:
data
that means that
str[0] is d
str[1] is a
str[2] is t
str[3] is a
str[4] is 0 or '\0', whatever you call it
but what is str[5] through str[29]? they are zilch, nada, undefined, garbage. therefore when you copy all 30 elements of str into str2 you copy the same worthlessness. Only copy the used elements of str, not all the elements of str (use strlen() to figure out how many elements were used) or use the strcpy() function to do the copying for you.
2) the second problem is this line:
str2[34] = 't';
there are actually two problems here, too. First, there is no element str2[34] in str2. Since str2 is declared as having 34 elements by this line:
char str2[34];
the last element of str2 is str2[33]. Remember, the values of array indexes start at zero, not one. So valid indexes for str2 range from 0 to 33, not 0 t0 34, or even 1 to 34.
The second problem is that in order to be a string, str2 needs to have the null terminating char and str2 doesn't have a null terminating char. Therefore, str2 is a char array, but it is not a string, and therefore it can't be used when trying to open an ifstream.
your syntax with the ofstream is appropriate otherwise.