如果你看一下the documentation for erase,你會看到:
basic_string& erase(size_type index = 0, size_type count = npos);
什麼是你s.erase(i, '\n')
情況是,'\n'
角色 - 這與ASCII碼10換行符 - 是匹配的count
參數,則造成10要刪除的字符。這是因爲char
類型是一個整體類型,並受標準轉換爲其他較大的整數類型,如size_type
(請參閱標準中的整體促銷 - draft here)。
相反,你應該使用std::string::find
找到偏移/指數在評論的開始和終止,並計算字符刪除的數量....
如果你看一下find
...
size_type find(const basic_string& str, size_type pos = 0) const;
...你會看到有一個pos
參數,默認爲0 - 這是開始搜索str
的字符串的偏移量。所以,你可以得到一個範圍內構成一個C風格/* ... */
評論鏈接這個字符:
while (true)
{
std::string::size_type from = line.find("/*");
if (from == std::string::npos)
break;
// a comment begins inside the line
std::strings::size_type to = line.find("*/", from);
if (to != std::string::npos)
line.erase(from, to - from);
else
line.erase(from); // rest of the line...
}
上面沒有溶液滴......你應該想想如何與/*
線後,辦理行但沒有匹配*/
。這不是特別困難,但是如果我不讓你做某件事,你將不會學習。
另外,而非讀取該文件一次一個字符...
while (!(filein.eof()))
{
ch=filein.get();
s.insert(i,1,ch);
i++;
}
...你可以(假設你不處理一個二進制文件,可以合法地包含NUL '\0'
字符)簡單地說...
if (std::getline(filein, s, '\0'))
{
...it_worked, use s here...
}
else
std::cerr << "error reading from filein\n";
第二個要擦除的參數不是一個字符。 – drescherjm
你的程序需要一個cpp文件,而不是二進制/可執行文件,對不對?你是否必須專門使用字符串類及其方法? – user3412759
是的,該程序確實需要一個cpp文件。我也必須使用一個字符串。 – user3412706