【发布时间】:2016-12-01 14:33:57
【问题描述】:
我有一个文件 1.txt 用一行字
- 一只猫破产了
- 列表项
- 那里有东西
我搜索一个单词 List 并将整行复制到新文件 2.txt 列表项。
我该怎么做? 谢谢。
【问题讨论】:
我有一个文件 1.txt 用一行字
我搜索一个单词 List 并将整行复制到新文件 2.txt 列表项。
我该怎么做? 谢谢。
【问题讨论】:
这是你的做法:
#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;
}
【讨论】: