Hello Lucyzzz,
I have always felt that knowing what you did wrong first helps you to understand what you need to fix and it may also help to understand the code that
seeplus has posted.
To start with:
void myFunction(vector<string> books)
. First this needs a better name. Something like "PrintBooks", "PrintTitles" or something else that describes what the function does.
Next is the parameter. Passing variables like "bool", "char", "int" and "double" by value means that the compiler is making a copy of the value and creating a local variable for the function. For these simple types that is not a problem.
When you pass more complicated variables like "std::string" and "std::vector" these are better passed by reference so that the program does not have to take the time or waste space making a copy. It will use what was defined somewhere else.
Making the parameter "const" is kind of 50/50. The function only uses the vector, but the "const" is a safety measure to make sure it is not changed in the function. This way the compiler will complain if you do something that tries to change a value in the vector. Other times you leave the "const" off because you want to change the value(s) in a vector.
All that is left here is the "cout" to print the titles.
In "main" I started out with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
int main()
{
const std::string PATH{ "./" }; // <--- A default path, i.e., the current working directory.
//const std::string PATH{ "C:/.../.../" };
ifstream inFile(PATH + "Books.txt");
//inFile.open("Books.txt");
//Check for Error
while (inFile.fail()) // <--- The more often preferred method "while (!inFile)". Will check more than just the "fail" bit.
{
string name;
cerr << "Error opening File\n";
cout << "Provide a valid fileName.txt please.\n";
// <--- You might want to provide available file name(s) and or path.
cin >> name;
inFile.open(PATH + name);
}
| |
Since the directions mention a path I added lines 3 and 4. You could copy line 4 as many times as you need and set up a different path switching the comments as needed.
You will find that line 6 is the more often used way of using the overloaded ctor of the streams to define the variable used and open the file at the same time. Should this fail to open the file the ".open" in the while loop will work since the file stream variable has already been defined.
The next while loop I think will work except that I have no idea what the input file looks like. So I do not know if it will actually work.
Also with out the input file I do not see any reason for the string stream unless you need the practice.
The call to "std::sort" looks OK, but could be a problem if you try to sort titles with upper and lower case letters. Some titles may not sort properly. Just something to keep in mind.
Understanding this might help to understand what
seeplus did.
Andy