我有一個字符串(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