467,879 Members | 1,242 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,879 developers. It's quick & easy.

input streams, setw(), and strings vs. char*?


If setw() is being used to limit how many characters are pulled from
a stream, should the # of characters taken from the stream depend on
whether the stream is being sent to a std::string or a char*?

string s1;
char s2[256];
cin >> setw(4) >> s1;
cin >> setw(4) >> s2;

(I've found there to be a difference between compilers -- on some,
they results are identical (ie, 3 characters pulled), and on others, the
string receives a 4th character)

Thanks,
Matt

----------------------------------------------------------------------
#include<iostream>
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
int main(void)
{
string s;
char buffer[256];
istringstream is1("0123456789");
is1 >> setw(4) >> s;
is1.seekg(0);
is1 >> setw(4) >> buffer;

cout << "s = " << s << endl;
cout << "buf= " << buffer << endl;

return 0;
}
Jul 19 '05 #1
  • viewed: 9254
Share:
1 Reply

"Matthew David Hills" <hi***@Stanford.EDU> wrote in message
news:bj**********@news.Stanford.EDU...

If setw() is being used to limit how many characters are pulled from
a stream, should the # of characters taken from the stream depend on
whether the stream is being sent to a std::string or a char*?

string s1;
char s2[256];
cin >> setw(4) >> s1;
cin >> setw(4) >> s2;

(I've found there to be a difference between compilers -- on some,
they results are identical (ie, 3 characters pulled), and on others, the
string receives a 4th character)

Thanks,
Matt


Its a good point, and the answer is yes the number should vary. The reason
is that setw is being used for subtly different reasons in the two cases.
For std::string setw is that maximum numbers of characters to be extracted,
for char* setw is intended as the size of the array that the char* is
pointing at. Since C style strings require a null terminator only setw - 1
characters can be extracted.

john
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Henry Jordon | last post: by
2 posts views Thread by tvn007 | last post: by
30 posts views Thread by Richard | last post: by
1 post views Thread by Gaijinco | last post: by
4 posts views Thread by Sudip | last post: by
17 posts views Thread by Christoph Scholtes | last post: by
reply views Thread by MrMoon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.