getline(param1,param2,param3)在c ++,linux中的用法

时间:2014-11-06 15:37:40

标签: c++ linux delimiter getline

...可能是一个非常简单的问题,但我要编写一个简单的c ++代码来使用分隔符解析字符串,我希望分隔符包含多个空格(实际上是一个或多个空格)。我的问题是,有可能这样做吗?我的示例代码是:

#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstring>
#include <sstream>
using namespace std;

int main()
{

        string str="HELLO     THIS IS    888and777";

        char buf[1000];
        getline(buf, 1000);
        string str(buf);

        stringstream stream(buf);
        string toStr;

        getline(stream, toStr,'      ');//here the delimiter is six spaces
        string str1=tostr;

        getline(stream, toStr,'  ');//here the delimiter is two spaces
        string str2=tostr;

        getline(stream, toStr,'   ');//here the delimiter is three spaces
        string str3=tostr;

        cout<<str1<<"\t"<<str2<<"\t"<<str3<<endl;
return 0;
}

但是,我不能使用多个字符的分隔符。请问任何想法。 我收到以下错误:

error: invalid conversion from ‘void*’ to ‘char**’
error: cannot convert ‘std::string’ to ‘size_t*’ for argument ‘2’ to ‘__ssize_t getline(char**, size_t*, FILE*)’

1 个答案:

答案 0 :(得分:0)

std::getline()使用的分隔符纯粹是一个单独的角色。要接受字符串,需要一个非平凡的算法来保证合适的性能。此外,使用'x'定义的实体通常需要生成个人char

对于这个例子,我认为最简单的方法是简单地直接对字符串进行标记:

#include <tuple>
#include <utility>
#include <string>
#include <iostream>

std::pair<std::string, std::string::size_type>
get_token(std::string const& value, std::string::size_type pos, std::string const& delimiter)
{
    if (pos == value.npos) {
        return std::make_pair(std::string(), pos);
    }
    std::string::size_type end(value.find(delimiter, pos));
    return end == value.npos
        ? std::make_pair(value.substr(pos), end)
        : std::make_pair(value.substr(pos, end - pos), end + delimiter.size());
}
int main()
{
    std::string str("HELLO      THIS IS    888and777");
    std::string str1, str2, str3;
    std::string::size_type pos(0);
    std::tie(str1, pos) = get_token(str, pos, "      ");
    std::tie(str2, pos) = get_token(str, pos, "  ");
    std::tie(str3, pos) = get_token(str, pos, "   ");

    std::cout << "str1='" << str1 << "' str2='" << str2 << "' str3='" << str3 << "'\n";
}