[英]Strange behaviour using std::istringstream with '>>' operator
我注意到下面非常簡單的程序有一種奇怪的行為。
#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
std::string data = "o BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n";
std::istringstream iss(data);
std::string line;
std::string type;
while (std::getline(iss, line, '\n'))
{
iss >> type;
std::cout << type << std::endl;
}
getchar();
return (0);
}
輸出如下:
v
v
v
但我想要以下一個:
o
v
v
我試過這個解決方案:
#include <iostream>
#include <sstream>
#include <string>
int main(void)
{
std::string data = "o BoxModel\nv 1.0f, 1.0f, 1.0f\nv 2.0f, 2.0f, 2.0f\n";
std::istringstream iss(data);
std::string line;
std::string type;
iss >> type;
std::cout << type << std::endl;
while (std::getline(iss, line, '\n'))
{
iss >> type;
std::cout << type << std::endl;
}
getchar();
return (0);
}
但輸出如下:
o
v
v
v
有人能幫幫我嗎? 非常感謝您的幫助。
調用getline后,從stringstream的緩沖區中刪除第一行。 第一個換行符后的字符串中的單詞是“v”。
在while循環中,使用該行作為輸入創建另一個字符串流。 現在從這個字符串流中提取您的類型字。
while (std::getline(iss, line, '\n'))
{
std::istringstream iss2(line);
iss2 >> type;
std::cout << type << std::endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.