解析 space 分隔字符串时,使用 getline 比 stringstream::operator>> 有什么优势吗?
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;
}
}
我一直使用前者,但我想知道使用后者是否有任何优势?我通常总是使用前者,因为我觉得如果有人将字符串更改为逗号分隔字符串,那么我需要做的就是放入一个新的分隔符,而 operator>>
会读入逗号。但是对于space定界,好像没有区别。
std::getline()
和 operator>>
用于不同的目的。这不是哪一个比另一个更有优势的问题。使用更适合手头任务的那个。
operator>>
适用于 formatted input。它读入并解析许多不同的数据类型,包括字符串。如果输入流上没有错误状态,它会跳过前导空格(除非输入流上的 skipws
标志被禁用,例如使用 std::noskipws
操纵器),然后它读取并解析字符直到遇到空格、不属于正在解析的数据类型的字符或流的末尾。
std::getline()
仅适用于 unformatted input 个字符串。如果输入流上没有错误状态,它不会跳过前导空格,然后读取字符,直到遇到指定的分隔符(如果未指定,则为 '\n'
)或流的末尾。
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;
}
}
我一直使用前者,但我想知道使用后者是否有任何优势?我通常总是使用前者,因为我觉得如果有人将字符串更改为逗号分隔字符串,那么我需要做的就是放入一个新的分隔符,而 operator>>
会读入逗号。但是对于space定界,好像没有区别。
std::getline()
和 operator>>
用于不同的目的。这不是哪一个比另一个更有优势的问题。使用更适合手头任务的那个。
operator>>
适用于 formatted input。它读入并解析许多不同的数据类型,包括字符串。如果输入流上没有错误状态,它会跳过前导空格(除非输入流上的 skipws
标志被禁用,例如使用 std::noskipws
操纵器),然后它读取并解析字符直到遇到空格、不属于正在解析的数据类型的字符或流的末尾。
std::getline()
仅适用于 unformatted input 个字符串。如果输入流上没有错误状态,它不会跳过前导空格,然后读取字符,直到遇到指定的分隔符(如果未指定,则为 '\n'
)或流的末尾。