|
-
June 16th, 2011, 05:12 PM
#1
Searching an input .txt file for a key string
Hey everyone,
I am creating an application to output many small text files from a large input text file. I am familiar with the getline function. What I usually do is put an entire line (from the .txt file) into a string (call it string_a), and then use a pointer to find the key character of the line I need to detect. After that, I write any proceeding text to an output .txt file.
Here is my question:
What if I am looking for more than just a single key character to trigger my program to start writing to the output file? Let's say I want to look for a key phrase. Let's say string_a contained the following text:
Ro, Key: 480000030 Name:AvTech, Id:20, Trip Offset:859500
I want to write the information after 'Name:' to my output file. Is there an effective way to search a large .txt file for the string 'Name:' ?
Thanks in advance.
-
June 16th, 2011, 08:30 PM
#2
Re: Searching an input .txt file for a key string
you could put the line into a STL string, and call its member function "find()" .
-
June 20th, 2011, 05:28 PM
#3
Re: Searching an input .txt file for a key string
I have tried that. No luck. Here are the issues I am facing:
1. .find(substring) function returns a value of -1 as a type size_t when substring is not found. It seems like my code isn't doing the comparison right. I have tried comparing the return value to -1 as well and it didn't work.
Here is some sample code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstddef>
using namespace std;
int main()
{
ifstream datain;
datain.open("test.txt");
int start = 1;
string str;
string taskname("AvTech");
size_t key 2 = -1;
while(start)
{
if (str.find(taskname) != key2)
{
getline(datain,str); //Continue moving through the .txt file
}
else
{
start = 0; // It appears to jump to this point in the loop
// the first time it enters the loop
}
}
return 0;
}
Any ideas?
-
June 20th, 2011, 06:10 PM
#4
Re: Searching an input .txt file for a key string
Thankfully, the substring I am looking for always appears in the same location within the line of the input file. I was able to determine that position and modify the condition for my loop to break accordingly. It's crappy code, but it will work for me.
Does anyone have a better idea how to make it more robust?
-
June 20th, 2011, 09:19 PM
#5
Re: Searching an input .txt file for a key string
if NOT found, the return value is string::npos
Code:
bool found = false;
while (!found && getline(datain,str))
{
if (str.find(taskname) != string::npos)
found = true;
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|