在輸入輸出流,字符串(意思是兩個C字符串和C++字符串)幾乎沒有任何的格式要求。任何和所有字符被提取爲一個字符串僅直到一個空白字符被發現,或直至流的末尾被捕獲。在你的榜樣,你使用意在吃起來的重要數據之間的逗號的字符串,但您所遇到的輸出是我剛纔解釋的行爲的結果是:dummy
字符串不只是吃了逗號,但也字符序列的其餘部分直到下一個空白字符。
爲了避免出現這種情況,您可以使用char
作爲虛擬變量,其中只有一個字符的空間。如果你正在尋找把Apple 1
成一個字符串,你需要一個格式化提取,因爲格式化提取operator>>()
只讀取,直到空白。在這裏使用相應的功能是std::getline()
:
string c;
char dummy;
if ((stream >> a >> dummy >> b >> dummy) &&
std::getline(stream >> std::ws, s))
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
{
}
清除換行後的格式化的提取也是必要的,這就是爲什麼我用std::ws
清除前導空格。我還使用了if
語句包含以判斷它成功與否的提取。
任何平滑的方式做到這一點會幫助我極大。
您可以使用std::ctype<char>
面流中充滿語言環境的逗號字符的類型設置爲空白字符。這將使得不需要使用虛擬變量。這裏有一個例子:
namespace detail
{
enum options { add, remove };
class ctype : public std::ctype<char>
{
private:
static mask* get_table(const std::string& ws, options opt)
{
static std::vector<mask> table(classic_table(),
classic_table() + table_size);
for (char c : ws)
{
if (opt == add)
table[c] |= space;
else if (opt == remove)
table[c] &= ~space;
}
return &table[0];
}
public:
ctype(const std::string& ws, options opt)
: std::ctype<char>(get_table(ws, opt)) { }
};
}
class adjustws_impl
{
public:
adjustws_impl(const std::string& ws, detail::options opt) :
m_ws(ws),
m_opt(opt)
{ }
friend std::istream& operator>>(std::istream& is,
const adjustws_impl& manip)
{
const detail::ctype* facet(new detail::ctype(manip.m_ws, manip.m_opt));
if (!std::has_facet<detail::ctype>(is.getloc())
{
is.imbue(std::locale(is.getloc(), facet));
} else
delete facet;
return is;
}
private:
std::string m_ws;
detail::options m_opt;
};
adjustws_impl setws(const std::string& ws)
{
return adjustws_impl(ws, detail::add);
}
adjustws_impl unsetws(const std::string& ws)
{
return adjustws_impl(ws, detail::remove);
}
int main()
{
std::istringstream iss("10,1.546,Apple 1");
int a; double b; std::string c;
iss >> setws(","); // set comma to a whitespace character
if ((iss >> a >> b) && std::getline(iss >> std::ws, c))
{
// ...
}
iss >> unsetws(","); // remove the whitespace classification
}
字符啞將修復它(第二個是吃了輸入) –
@DieterLücking'字符串假人;'德哦。我盯着像白癡一樣的代碼,並沒有看到它:) – jrok
@DieterLücking是的,它已經改進爲輸出10和1.546,但我需要'蘋果1',並沒有得到任何東西,我現在正在'Apple'但仍然不是「Apple 1」。有任何想法嗎? –