use*_*711 -2 c++ string inputstream file ifstream
我有一个输入文件如下 -
BEGIN
ABC
DEF
END
BEGIN
XYZ
RST
END
Run Code Online (Sandbox Code Playgroud)
我必须提取从BEGIN到END的所有内容并将它们存储在一个字符串中.所以,从这个文件中我将有两个字符串.我ifstream用来读取输入文件.我的问题是,如何解析输入文件以获取从一个BEGIN到下一个END的所有内容.getline()有字符作为分隔符,而不是字符串.我尝试的另一种方法是将输入文件中的所有内容复制到字符串中,然后根据该字符串解析字符串.find().但是,在这种方法中,我只得到第一个BEGIN到END.
有没有什么办法可以将所有内容存储在输入文件的字符串中,直到某个字符串出现(END)?
为了存储目的,我使用一个vector<string>存储.
用正确的名称替换文件名.
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
#include <string>
using namespace std;
int main()
{
char filename[] = "a.txt";
std::vector<string> v;
std::ifstream input(filename);
string temp = "";
for(std::string line; getline( input, line ); )
{
if(string(line) == "BEGIN")
continue;
else if(string(line) == "END")
{
v.push_back(temp);
temp = "";
}
else
{
temp += string(line);
}
}
for(int i=0; i<v.size(); i++)
cout<<v[i]<<endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
107 次 |
| 最近记录: |