将一行文本从文件复制到c ++中的字符串

时间:2012-07-11 23:16:08

标签: c++ parsing

我需要从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;    
}

1 个答案:

答案 0 :(得分:0)

你只需要一个循环即可完成此任务。你的循环应该是这样的:

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();
}

我还建议你不要混用int和size_t类型。例如,字符应声明为size_t,而不是int。