|
-
July 10th, 2002, 09:00 PM
#1
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.
-
July 11th, 2002, 04:23 AM
#2
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.
-
July 11th, 2002, 04:46 AM
#3
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.
-
July 11th, 2002, 05:56 AM
#4
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.
-
July 11th, 2002, 09:23 AM
#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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|