File read / find - miss 1st line in file
May 3, 2013 at 1:07pm UTC
Hi,
I wrote the below code to find the line with "abc" as my parameter to strTosearch. I expected to the line 1st line but, this function always match the 2nd line. What am I missing here?
I wanted "found" to be "abc def hgi SSS".
Can someone please help to understand & fix this? Thanks.
Code in main()
String found=GetstringColSamLine("mytext.txt", "abc");
File name - mytext.txt
abc def hgi SSS
abc ppp yyy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
string GetstringColSamLine(string routerFileName, string strTosearch)
{
string str;
string line;
string strone;
unsigned long offset;
ifstream fileToSearch;
fileToSearch.open (routerFileName.c_str());
if (fileToSearch)
{
while (getline(fileToSearch, line))
{
if ((offset=line.find(strTosearch, 0)) != string::npos)
{
strone=line;
}
}
}
fileToSearch.close();
return (strone);
}
Mathew
May 3, 2013 at 1:37pm UTC
1 2 3
while (getline(fileToSearch, line))
if (line.find(strTosearch, 0) != string::npos)
return line;
May 3, 2013 at 1:37pm UTC
Your loop does not stop when it finds the target string. So in fact strone will contain the last occurence of the target string.
1 2 3 4 5 6 7
while (getline(fileToSearch, line))
{
if ((offset=line.find(strTosearch, 0)) != string::npos)
{
strone=line;
}
}
You could either insert break statement inside the loop in the case when the target string is found or rewrite the condition of the loop.
Last edited on May 3, 2013 at 1:38pm UTC
May 5, 2013 at 2:13am UTC
Hi
Thanks. That fixed the problem. I did not catch it was not coming from the loop.
So this is solved.
Thanks again.
Mathew
Topic archived. No new replies allowed.