CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Sep 2001
    Posts
    5

    Read specified number of char from istream

    Hi,

    What is the most efficient way to read specified number (n) of characters from an istream to a std::string?

    Thanks.

  2. #2
    Join Date
    Jun 2002
    Location
    Germany
    Posts
    1,557
    Set the field width for input, read the string, set the string to the just-read-in input.

    Chris.

    #include <iostream>
    #include <iomanip>
    #include <string>
    using namespace std;

    void read_it(void)
    {
    char buffer[81];
    cin >> setw(sizeof(buffer) / sizeof(char)) >> buffer;
    string the_string = buffer;
    }

    int main(int argc, char* argv[])
    {
    read_it();

    return 1;
    }

    You're gonna go blind staring into that box all day.

  3. #3
    Join Date
    Jun 2002
    Posts
    137
    to read the char from the istream,
    you can use like the following:

    Code:
    istream in;
    streambuf* p = in.rdbuf()
    std:string += p->sgetc()

    or you can use p->sbumpc() to get the char too.
    the difference between sgetc() and sbumpc() is that:
    sgetc() return the current read char but donot move to next position, while sbumpc() will move to next position.

  4. #4
    Join Date
    Jun 2002
    Posts
    224
    I don't know much about stl, so please double-check.

    Code:
    void read( string& dst, int count, istream& is )
    {
      dst.resize(count, 0);
      is.read( dst.begin(), count );
    }
    
    // usage
    string s;
    read(s, 10, cin);
    Regards,
    ZDF

    What is good is twice as good if it's simple.
    "Make it simple" is a complex task.

  5. #5
    Join Date
    Sep 2001
    Posts
    5
    This is what I need. Thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured