【问题标题】:Copy one line of text from a file to a string in c++将文件中的一行文本复制到c++中的字符串
【发布时间】:2012-07-11 23:16:07
【问题描述】:

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

【问题讨论】:

  • 查看编辑(我添加了您当前正在阅读的文本,因为它不会让我在没有更多文字的情况下发表评论)

标签: c++ parsing


【解决方案1】:

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

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。

【讨论】:

  • eof 并不是 getline 失败的唯一原因。 getline() 的返回值是用来测试的。使用while ( getline(in_stream,str) )
猜你喜欢
  • 2021-05-24
  • 2016-07-30
  • 2011-01-25
  • 2016-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多