C++/Read word from text file.
Expert: Zlatko - 10/29/2010
QuestionHi !
Im creating program that will read one word from the text
file. The word i want my program to read is PROFILE. I am
beginer so I dont know much about C++ programing. I realy
need help because I almost finished my program, I just need
this bit of code.
The file with word PROFILE in it will be named profile.txt.
AnswerHello Krystian
I could help you more if I knew what the profile.txt looked like and what you needed to do once the word PROFILE was found. For now I can give you the sample code below to show you how to open a file, read it's lines, and search for a line that starts with PROFILE.
I hope that helps you. Let me know if there is something in the program that you don't understand.
Best regards
Zlatko
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
void readFromFile(void)
{
// open the file and check that it was found
ifstream in("profile.txt");
if ( ! in.good())
{
cout << "Cannot open the file\n";
}
else
{
while(in.good())
{
// read the file lines into a string called line
string line;
getline(in, line);
// compare the first 7 characters of line with the word "PROFILE"
// This comparison is case sensitive.
if (line.compare(0, 7, "PROFILE") == 0)
{
cout << "Found the profile line!\n";
// what you do here is up to you
}
else
{
cout << "Read line: '" << line << "'\n";
}
}
}
}
int main(void)
{
readFromFile();
}