我有一个字符串(ifstream的)与下一行:如何使用条件擦除一条线?
foo
foo+..
foo
而且,我想知道如何让行,那里是一个符号+并删除其余线路:
foo+..
到流转换为字符串,我用:
string stream((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
我有一个字符串(ifstream的)与下一行:如何使用条件擦除一条线?
foo
foo+..
foo
而且,我想知道如何让行,那里是一个符号+并删除其余线路:
foo+..
到流转换为字符串,我用:
string stream((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
这个怎么样的替代解决方案:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool HasNoPlus(const string &value)
{
return value.find('+') == string::npos;
}
int main(int argc, char* argv[])
{
ifstream ifs("d:\\temp\\test.txt");
vector<string> out;
remove_copy_if(istream_iterator<string>(ifs),
istream_iterator<string>(),
back_inserter(out),
HasNoPlus);
return 0;
}
对'ifs'和'close'调用的测试都是不必要的。如果数据流处于不良状态,则不会复制任何内容,并且该数据流在其范围的末尾仍会被关闭。 – 2012-01-04 10:23:01
@MatthieuM .:感谢您的建议 - 编辑我的代码。 – nabulke 2012-01-04 10:34:47
int pos_plus = str.find('+');
int pos_beg = str.find_last_of('\n',pos_plus);
int pos_end = str.find_first_of('\n',pos_plus);
if(pos_beg == pos_plus) pos_beg = 0;
if(pos_end == pos_plus) pos_end = str.size();
str.erase(pos_beg,pos_end-pos_beg);
这是一个C++问题,所以使用'string'方法而不是手动搜索该字符串并使用'strcpy'。但总体思路是有效的。 – 2012-01-04 09:14:30
@Clement Bellot,感谢您的算法。 – Duglas 2012-01-04 09:35:15
要过滤来自ifstream的输入(如您的评论中所述),请使用新的ostringstream。
从ifstream(getline)中读取每一行,并检查它是否通过了过滤条件。
如果它通过,将它附加到ostringstream。
当你从ostringstream中取出字符串时,你将得到过滤后的字符串。
我已经有一个字符串使用:_string流((std :: istreambuf_iterator
如果您不需要中间串,你可以从ifstream
直接复制到一个新的ofstream
,使用标准的算法:
#include <algorithm>
#include <fstream>
#include <iterator>
#include <string>
struct has_no_plus {
bool operator()(const std::string& str)
{
if (str.find('+') != std::string::npos)
return false;
else
return true;
}
};
int main()
{
std::ifstream ifs("file.txt");
std::ofstream ofs("copy.txt");
std::remove_copy_if(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(ofs, "\n"),
has_no_plus());
// or alternatively, in C++11:
std::copy_if(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::ostream_iterator<std::string>(ofs, "\n"),
[](const std::string& str)
{
return str.find('+') != str.npos;
});
}
有什么你试过了吗?请显示您的代码的相关部分,以便我们了解您如何代表/保持您的字符串。 – Mat 2012-01-04 09:08:05
您的_one_字符串中有许多行由回车/换行符分隔。正确? – nabulke 2012-01-04 09:08:55
您是从控制台还是从文本文件读取?单个字符串中的字符串是否包含'\ n''字符或多个字符串?你到目前为止有什么? – 2012-01-04 09:09:06