Hello everyone,
I'm stuck with this problem. For example, I have a text file:
"Hello
I Am
Liz Hurley"
How can I load the file and store "Hello" for str1, "I Am" for str2, & "Liz Hurley" for str3?
I came up with getline, but it doesn't work :( Thank you.
Have a look at this tutorial. There's a sample at the top and a few others further down which you can easily adapt. Instead of the test in quotation marks just use the string . eg myfile << str1; etc
You can then read what you have on the file using notepad or similar until you write code to read your file.
Thank you guys Kermort and Thomas. However, my getline functions didn't work at all :( The result I got are blanks which I assume it read nothing from the file.
1000 pardons because I misread your comment about strings. However, try this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::fstream inFile("getstringfile.txt");
std::string temp = "";
if (inFile.is_open())
{
while (std::getline(inFile, temp))
std::cout << '*' << temp << '*' << std::endl;
}
else
std::cout << "File not opened\n";
return 0;
}
Text file getstringfile.txt I used is:
Hello
I Am
Liz Hurley
And the output is:
*Hello*
*I Am*
*Liz Hurley*
Program ended with exit code: 0
The asterisks are there to verify each line was read as a single strings.
PS You wanted str1, str2, ... instead of temp. This means you read in separate variables but I'll leave that to you. It's not a complicated adaptation, and better still, keep your program and make the few necessary changes. :)
My pleasure. On reflection the adaptation might need a hint:
1 2 3 4 5 6 7 8 9
if (inFile.is_open())
{
while (std::getline(inFile, str1) && std::getline( ... some more stuff for the other strings ){}
std::cout << '*' << str1 << '*' << std::endl;
//some more lines for the other strings
}
else
std::cout << "File not opened\n";