2016-12-01 2 views

Antwort

0

Hier ist, wie Sie das tun:

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

Dies funktioniert wie ein Charme, erstaunliche Codierung !! Danke :) – Insanebench420

Verwandte Themen