gpt4 book ai didi

c++ - ostream_iterator 不跳过空格

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:43:48 24 4
gpt4 key购买 nike

我有这样的代码,我很困惑为什么字符串中的空格没有被修剪?

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
#include <sstream>
#include <iterator>

using namespace std;

template <typename T> //T type of stream element
void trimspace2(std::string str) //user istream_iterator suppose it's a number string
{
istringstream iss(str),ise("");
ostringstream oss(str);
copy(istream_iterator<T>(iss),istream_iterator<T>(ise),ostream_iterator<T>(oss," "));
cout << str << endl;
}

int main()
{
std::string str = " 20 30 100 ";
trimspace2<int>(str);
return 0;
}

输出是

" 20 30    100  "

与输入相同。

最佳答案

您正在函数末尾输出 str,即您的输入参数。将最后一行更改为:

cout << oss.str() << endl;

哦,你不应该使用 str 来构造 oss:

ostringstream oss;

根据您在下面的评论,我认为您想要的是:

template <typename T>
void trimspace2(std::string &str)
{
istringstream iss(str);
ostringstream oss;
copy(istream_iterator<T>(iss),istream_iterator<T>(),ostream_iterator<T>(oss," "));
str = oss.str();
}

关于c++ - ostream_iterator 不跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24545748/

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