gpt4 book ai didi

c++ - noskipws 有什么问题?

转载 作者:行者123 更新时间:2023-11-27 23:44:15 27 4
gpt4 key购买 nike

我在使用以下模板函数时遇到问题。

/// Remove leading and trailing space and tab characters from a string.
/// @param[out] result the string to remove leading and trailing spaces from
template<class T>
void TrimString(std::basic_string<T>& str)
{
basic_string<T> s, strRslt;

basic_stringstream<T> strstrm(str);

// we need to trim the leading whitespace using the skipws flag from istream.
strstrm >> s;

if(!s.empty())
{
do
{
strRslt += s;
}while(strstrm >> noskipws >> s);
}


str = strRslt;

return;

}

此单元测试通过:

[TestMethod]
void TestNarrowStringTrim()
{
std::string testString = " test";
TrimString(testString);
Assert::IsTrue(testString == "test");
}

所以我也希望下面的单元测试能够通过:

[TestMethod]
void TestNarrowStringTrim()
{
std::string testString = " test string";
TrimString(testString);
Assert::IsTrue(testString == "test string");
}

但是由于某些原因,函数末尾的str的值为“test”

谁能帮我解决这个问题?

因为它可能(几乎可以肯定)相关,所以我将 Visual C++ 与 Visual Studio 2012 结合使用。

noskipws 的 MSDN 文章也不同于 ccpreference.com 文章。我已将这两篇文章链接起来进行比较。

MSDN noskipws

cppreference.com noskipws

最佳答案

从流中读取字符串在遇到空格时停止。由于您已禁用 skipws,因此读取的第一个字符是一个空格。因此读取空字符串并设置故障位。参见 https://en.cppreference.com/w/cpp/string/basic_string/operator_ltltgtgt .

VS 2012 实现可能是正确的(您的代码也因 gcc 而失败)只是文档很差。

根本不需要用到流,find和substr就简单多了:

template<class T>
void TrimString( std::basic_string<T>& str)
{
size_t begin = str.find_first_not_of(" \t");
if ( begin == std::string::npos )
{
str.clear();
}
else
{
size_t end = str.find_last_not_of(" \t");
str = str.substr( begin, end - begin + 1 );
}
}

或者更简单的是boost::trim():https://www.boost.org/doc/libs/1_68_0/doc/html/string_algo/usage.html#id-1.3.3.5.5

关于c++ - noskipws 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902079/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com