在String中调整String的大小

C++ Resizing String in String

本文关键字:String 调整      更新时间:2023-10-16

我想知道为什么我不能在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;