c++ - When parsing a space delimitated string, is there any advantage using getline over stringstream::operator>>?
问题描述
int main()
{
std::string s = "my name is joe";
std::stringstream ss{s};
std::string temp;
while(std::getline(ss, temp, ' '))
{
cout << temp.size() << " " << temp << endl;
}
//----------------------------//
ss = std::stringstream{s};
while(ss >> temp)
{
cout << temp.size() << " " << temp << endl;
}
}
I've always used the former, but I'm wondering if there's any advantage to using the latter? I've typically always used the former because I feel that if someone were to instead change the string to a comma delimitated string, then all I need to do is put in a new delimiter, whereas the operator>>
would read in the commas. But for space delimitation, it seems there is no difference.
解决方案
std::getline()
and operator>>
are intended for different purposes. It is not a matter of which one is more advantageous than the other. Use the one that is better suited for the task at hand.
operator>>
is for formatted input. It reads in and parses many different data types, including strings. If there is no error state on the input stream, it skips leading whitespace (unless the skipws
flag on the input stream is disabled, such as with the std::noskipws
manipulator), and then it reads and parses characters until it encounters whitespace, a character that does not belong to the data type being parsed, or the end of the stream.
std::getline()
is for unformatted input of strings only. If there is no error state on the input stream, it does not skip leading whitespace, and then it reads characters until it encounters the specified delimiter (or '\n'
if not specified), or the end of the stream.
推荐阅读
- c# - FluentValidation:扩展方法在多个属性上应用相同的规则
- android - 通过 flatMap 提取数据不会调用 subscribe
- python - 如何更新 Sounddevice 的采样率?
- ruby-on-rails - Rails 将邮政编码连接到区域并根据结果进行搜索
- python - 使用 Selenium Python 在网页上找不到元素
- matlab - 求解线性方程组
- r - 在 R 中找不到函数“FUNcluster”
- java - RxJava2 UndeliverableException 在获取数据时发生方向变化
- javascript - 我如何在提到的频道上发布公告?
- php - 带复选框的多表单发送