问题
I am reading the following file:
File.txt
Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\018-1-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\A018-2-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\021-1-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\A021-2-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\022-1-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\022-2-R.xml Y:\Test\DOCUMENTS\DOCUMENTS\Flux Assurance 2\multi\ACTEPROC_OK\025-1-R.xml
Source code:
#include <iostream>
#include <vector>
#include <boost/iostreams/device/mapped_file.hpp>
#include <boost/iostreams/stream.hpp>
std::vector<string> readFile(string);
int main()
{
std::vector<string> res = readFile("file.txt");
return 0;
}
std::vector<string> readFile(string f)
{
boost::iostreams::stream<boost::iostreams::mapped_file_source> str(f);
std::vector<string> app;
for(string x; str >> x;)
{
app.push_back(x);
}
return app;
}//end
Problem:
Since There is a space Between Flux and Assurance 2, it considers space as a separator.
How can remove the separator, or explicitly identify what the separator is?
回答1:
This has nothing to with boost or memorymapping.
Firstly
str.unsetf(std::ios::skipws);
will prevent whitespace from being used as delimiter/skipped.
Secondly, I think (you don't mention any of that) you wanted to read by line:
for(std::string x; std::getline(str, x, '\n');)
{
app.push_back(x);
}
As you can see you can already specify the delimiter.
Lastly, consider using a parser generator. See e.g. here:
- How to parse space-separated floats in C++ quickly?
Which contains an example that uses Boost Spirit to parse from a memory-mapped file.
来源:https://stackoverflow.com/questions/21431518/read-text-file-using-boost-mmap