Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > input streams, setw(), and strings vs. char*?

Reply
Thread Tools

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

 
 
Matthew David Hills
Guest
Posts: n/a
 
      09-05-2003

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;
}
 
Reply With Quote
 
 
 
 
John Harrison
Guest
Posts: n/a
 
      09-05-2003

"Matthew David Hills" <(E-Mail Removed)> wrote in message
news:bj8mqj$4pl$(E-Mail Removed)...
>
> 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


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Entering strings as user input but interpreting as Python input (sortof) Chris Carlen Python 1 09-18-2007 01:58 AM
Strings, Strings and Damned Strings Ben C Programming 14 06-24-2006 05:09 AM
Getting lower-bound and upper-bound of strings input Rhiner Dan C++ 1 03-27-2005 02:03 AM
Catching std::strings and c-style strings at once Kurt Krueckeberg C++ 2 11-17-2004 03:53 AM
input fields and strings Tim Fooy HTML 2 09-14-2004 06:37 AM



Advertisments