是否有一个附加到字符串的getline(istream,string,delim)?

时间:2011-11-17 17:05:48

标签: c++ boost std

这样可以避免复制。是什么东西在标准或提升这样做?

4 个答案:

答案 0 :(得分:3)

std::string mystring = "HELLO "; //initial string
int len = mystring.size(); //get initial length
mystring.resize(100); //resize so it's big enough
char* buffer = &mystring[len-1]+1; //get pointer to "spare" space
std::cin.get(buffer , 100-len, '\n'); //read into buffer, until newline
mystring.resize(len + std::cin.gcount()); //shrink to correct size

答案 1 :(得分:2)

您可以使用此成员功能(doc):

istream& getline (char* s, streamsize n, char delim );

读取数据,然后将该数据附加到字符串。

例如,您可以将此功能包装在您自己定义的函数中:

std::istream & getline(std::istream &in, std::string & str, char delim)
{
    char buf[1024];
    in.getline(buf, 1024, delim);
    str.append(buf, in.gcount());
    return in;
}

std::string s = "initial string";

getline(std::cin, s, '\n'); //should append to s

答案 2 :(得分:2)

由于没有现有的解决方案,我就想到了这一点:

istream& appendline(istream& is, string& str, char delim = '\n')
{
    size_t size = str.size();
    size_t capacity = str.capacity();
    streamsize spaceRemaining = capacity - size;

    if (spaceRemaining == 0)
    {
        capacity = max(static_cast<size_t>(8), capacity * 2);
        spaceRemaining = capacity - size;
    }

    // give getline access to all of capacity
    str.resize(capacity);

    // get until delim or spaceRemaining is filled
    is.getline(&str[size], spaceRemaining, delim);

    // gcount includes the delimiter but not the null terminator
    size_t newSize = size + is.gcount();

    // is failbit set?
    if (!is)
    {
        // if string ran out of space, expand and retry
        if (is.gcount()+1 == spaceRemaining)
        {
            is.clear();
            str.resize(newSize);
            str.reserve(capacity * 2);
            return appendline(is, str, delim);
        }
    }
    else if (!is.eof())
        --newSize;

    // resize string to fit its contents
    str.resize(newSize);
    return is;
}

答案 3 :(得分:0)

只需使用全局std :: getline而不是成员方法

stringstream s;
s << "line1\nline2";
string str;
while(std::getline(s, str)) cout << str;

输出:line1line2