在String中调整String的大小
C++ Resizing String in String
我想知道为什么我不能在cout执行期间在另一个字符串内调整字符串的大小。这里是我想做的例子,返回"表达式必须具有整型或无作用域枚举类型"
string tipa = to_string((stod(taxa)+price)*0.2);
cout << "nTip: $" + tipa.resize(tipa.size() - 4);
这是一个我偶然发现的解决方案的例子,但不知道为什么:
string tipa = to_string((stod(taxa)+price)*0.2);
tipa.resize(tipa.size() - 4);
cout << "nTip: $" + tipa;
有人能解释一下吗?
问题是:std::string::resize()
的返回类型是什么?如果您查看文档,您将看到它没有返回任何内容!它返回一个void
正确的调用方式是:
string tipa = to_string((stod(taxa)+price)*0.2);
tipa.resize(tipa.size() - 4); //you mutate the string here by resizing it, so the string inside it changes
cout << "nTip: $" + tipa; //you print the string that was changed in the previous line
老实说,我印象深刻的是,它甚至编译。我一开始就不知道这是怎么回事!
你不能std::cout
a void
!我想补充一点,实际上,这样裁剪浮点数是不好的。你应该先使用std::round
,然后裁剪它。考虑tipa
的长度小于4的情况。上面的代码肯定会崩溃。
你犯了一个致命的错误:根据文档,std::basic_string::resize
:
<标题> 返回值(没有)
标题>
函数的签名是:
void resize( size_type count );
注意这个函数是void
,这意味着你不能在表达式中使用它,因为它没有返回值std::string
编辑
下面是使用函数的正确方法,你发现的解决方案是非常错误的:
string tipa = to_string((stod(taxa)+price)*0.2);
tipa.resize(tipa.size() - 4);
cout << "nTip: $" + tipa;
相关文章:
- 为char数组调整zlib-zpipe
- 调整大小后指向元素值的指针unordered_map有效?
- cppcheck在const std::string[]上引发警告
- 在C++中调整向量中的索引
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 哪些库可以通过Opencv调整曝光率
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- Alt+Enter 在 Win32 应用中,管理大小调整和分辨率
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 在容量内调整矢量大小时的性能影响
- 如何更改大小(std::string)
- 调整我的std :: string时,角色缓冲区会发生什么
- 在String中调整String的大小