I need to copy one line of text from a text file in c++, I have a program to find the line inwhich a word resides, so I decided if I could just take each individual line and load it into a string I could search line by line, string by string to find the correct word and its position (in characters, not lines) in the file. Help would be greatly appreciated.
edit: I found the code I am using to locate the line
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include <conio.h>
using namespace std;
int main()
{
ifstream in_stream; //declaring the file input
string filein, search, str, replace; //declaring strings
int lines = 0, characters = 0, words = 0; //declaring integers
char ch;
cout << "Enter the name of the file\n"; //Tells user to input a file name
cin >> filein; //User inputs incoming file name
in_stream.open (filein.c_str(), ios::in | ios::binary); //Opens the file
//FIND WORDS
cout << "Enter word to search: " <<endl;
cin >> search; //User inputs word they want to search
while (!in_stream.eof())
{
getline(in_stream, str);
lines++;
if ((str.find(search, 0)) != string::npos)
{
cout << "found at line " << lines << endl;
}
}
in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer....
in_stream.seekg (0, ios::beg); // the seek goes here to reset the pointer.....
//COUNT CHARACTERS
while (!in_stream.eof())
{
in_stream.get(ch);
cout << ch;
characters ++;
}
//COUNT WORDS
in_stream.close ();
system("PAUSE");
return EXIT_SUCCESS;
}
You only need one loop to accomplish this. Your loop should look something like this:
while (getline(in_stream, str))
{
lines++;
size_t pos = str.find(search, 0);
if (pos != string::npos)
{
size_t position = characters + pos;
cout << "found at line " << lines << " and character " << position << endl;
}
characters += str.length();
}
I also recommend you don't mix int and size_t types. For example, characters should be declared as size_t, not int.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.