相关疑难解决方法(0)

如何迭代字符串的单词?

我正在尝试迭代字符串的单词.

可以假设该字符串由用空格分隔的单词组成.

请注意,我对C字符串函数或那种字符操作/访问不感兴趣.另外,请在答案中优先考虑优雅而不是效率.

我现在最好的解决方案是:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string s = "Somewhere down the road";
    istringstream iss(s);

    do
    {
        string subs;
        iss >> subs;
        cout << "Substring: " << subs << endl;
    } while (iss);
}
Run Code Online (Sandbox Code Playgroud)

有没有更优雅的方式来做到这一点?

c++ string split

2895
推荐指数
43
解决办法
214万
查看次数

当数据有空格时,用C++的流运算符>>读取格式化数据

我有以下格式的数据:

4:How do you do?
10:Happy birthday
1:Purple monkey dishwasher
200:The Ancestral Territorial Imperatives of the Trumpeter Swan

数字可以是1到999之间,字符串最多255个字符.我是C++的新手,似乎有些消息来源建议使用流的>>运算符提取格式化数据,但是当我想提取字符串时,它会停留在第一个空白字符处.有没有办法配置流只停止在换行符或文件结束时解析字符串?我看到有一种getline方法可以提取整行,但是我仍然需要手动将其拆分[有find_first_of],不是吗?

是否有一种简单的方法可以仅使用STL以此格式解析数据?

c++ stl stream formatted-input

13
推荐指数
3
解决办法
5185
查看次数

使用istream_iterator范围构造时无法访问向量


我试图编译这段代码片段但是我遇到了编译错误:(!用Visual Studio 2010编译

#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <iostream>

using namespace std;

int main() {
    string s( "Well well on" );
    istringstream in( s );
    vector<string> v( istream_iterator<string>( in ), istream_iterator<string>() );
    copy( v.begin(), v.end(), ostream_iterator<string>( cout, "\n" ) );
}
Run Code Online (Sandbox Code Playgroud)

错误:

Error   1   error C2228: left of '.begin' must have class/struct/union  c:\visual studio 2008 projects\vector test\vector test\main.cpp 13  vector test
Error   2   error C2228: left of '.end' must have class/struct/union    c:\visual studio 2008 projects\vector test\vector …
Run Code Online (Sandbox Code Playgroud)

c++ stl most-vexing-parse

2
推荐指数
1
解决办法
607
查看次数

标签 统计

c++ ×3

stl ×2

formatted-input ×1

most-vexing-parse ×1

split ×1

stream ×1

string ×1