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

  • Thread starter Matthew David Hills
  • Start date
M

Matthew David Hills

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;
}
 
J

John Harrison

Matthew David Hills said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top