C ++调整字符串中的字符串大小

时间:2016-09-06 19:43:57

标签: c++ string truncate

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

有人可以解释一下吗?

2 个答案:

答案 0 :(得分:2)

问题是: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一个void

我想补充一点,实际上,以这种方式裁剪浮点数是不好的。您应首先使用std::round,然后裁剪它。如果tipa的长度小于4,请考虑这种情况。上面的代码肯定会崩溃。

答案 1 :(得分:0)

你在这里犯了致命错误: 根据文档,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;