从文件中读取单词并将整行复制到另一个文件

时间:2016-12-01 14:33:57

标签: c++ file

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

  1. 一只猫破产了
  2. 列表项
  3. 有什么东西
  4. 我搜索单词列表并将整行复制到新文件 2.txt 列表项目。

    我该怎么做? 谢谢。

1 个答案:

答案 0 :(得分:0)

这是你如何做到的:

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