Hello! so for a project i am working on i have to ask users for the name of a txt file they wish to pull information from (a list of names) and pull information from said txt file into a 2d array. The thing is there can be not string, we can only use iostream and fstream. I have some code below but honestly, I'm not sure how to get user input and use that for the name of the text file. I know how to get user input for a c style string but how do i use the input for a file name?
for (int i = 0; i < 10; i++)
{
cout << "What is the name of your file?" << endl;
cin.getline(filename, 10);
}
This will ask the user to input the filename 10 times.
char filename[10];
What happens if the filename is more than 9 characters (1 character for null terminator) ?
Also, avoid magic numbers and remember to initialise your variables. Instead used name constants, like so
1 2 3 4 5 6 7
constint filename_len = ...
// zero initialise char array; choose whichever way you prefer
char filename[filename_len]{};
// OR
char filename[filename_len] = {};
// OR
char filename[filename_len] = { 0 };
inFile.open(filename.c_str());
c_str() is a member function of std::string not a char array. A char array is also known as a C-style string, so all you have to do is pass it as it is.
Thank you guys! i think I have managed to clear my code up a little now. I mistakenly though that the character array would need to be filled one character at a time thats why i used the for loop but now i see what you are saying. how does it look?
hm so my work has gone deeper now ad i wish to output the data that i pull in from fstream. for the most part i have it figured out but i an encountering problems when i output my data it comes in the form of
BlackPanther
IronMan
CaptainMarvel
Hulk
DeadPool
NickFury
Spiderman
Vision
ReedRichards
Antman
I think it has something to do with the way i am outputting my data (can someone double check my void print_out file? line 43) but i did this way before and it worked (that time the data for my char array was declared in my code however, not pulled from an external source) may I please have some Help?