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

Copy one line of text from a file to a string in c++

本文关键字:文本 一行 复制 字符串 c++ 文件      更新时间:2023-10-16

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

您只需要一个循环就可以实现这一点。你的循环应该是这样的:

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。