0

我需要从 C++ 中的文本文件中复制一行文本,我有一个程序可以找到一个单词所在的行,所以我决定是否可以只取每一行并将其加载到我可以搜索的字符串中逐行逐个字符串地查找正确的单词及其在文件中的位置(以字符为单位,而不是行)。帮助将不胜感激。

编辑:我找到了我用来定位该行的代码

#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;    
}
4

1 回答 1

0

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.

于 2012-07-11T23:59:07.837 回答