【问题标题】:Read from a file search for a word and copy the entire line to another file [closed]从文件中读取一个单词并将整行复制到另一个文件[关闭]
【发布时间】:2016-12-01 14:33:57
【问题描述】:

我有一个文件 1.txt 用一行字

  1. 一只猫破产了
  2. 列表项
  3. 那里有东西

我搜索一个单词 List 并将整行复制到新文件 2.txt 列表项。

我该怎么做? 谢谢。

【问题讨论】:

标签: c++ file


【解决方案1】:

这是你的做法:

#include <iostream>
#include <string>
#include <fstream> // to read from a file with std::fstream, and to write to a file with std::ofstream
#include <list> // to use std::list

int main()
{
    // this list will store all the lines of our file
    std::list<std::string> myList;

    std::fstream myFile("1.txt");
    if (!myFile)
    {
        std::cout << "File open failed." << std::endl;
    }
    else
    {
        std::string line;
        while (std::getline(myFile, line))
        {
            myList.push_back(line);
        }
    }
    myFile.close();

    // we create a dynamic array(myArray) to store the lines if they contain the word we are looking for
    std::string * myArray = new std::string[myList.size()];
    int count = 0;

    std::list<std::string>::iterator iter;
    iter = myList.begin();
    while (iter != myList.end())    // we will loop through all the elements of the list(myList)
    {
        std::string myString = *iter;
        // if we find the word we are looking for in our string(myString), we store the string in our array(myArray)
        if (!myString.find("List"))
        {
            myArray[count] = myString;
            count++;
        }
        iter++;
    }

    if (count == 0)
    {
        std::cout << "The word you are looking for doesn't exit in your file." << std::endl;
    }
    else
    {
        // if the word has been found then we write the entire line in a new file
        std::ofstream outFile("2.txt");
        if (!outFile)
        {
            std::cout << "File open failed." << std::endl;
        }
        else
        {
            for (int i = 0; i < count; i++)
            {
                outFile << myArray[i] << std::endl;
            }
        }
        std::cout << "The word you are looking for was found and a new file has been created." << std::endl;
    }

    // don't forget to deallocate the dynamic array (myArray)
    delete[] myArray;

    return 0;
}

【讨论】:

  • 这就像一个魅力,惊人的编码!谢谢你:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 2020-06-24
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多