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

Discussion in 'C++' started by Matthew David Hills, Sep 5, 2003.

  1. 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)


    using namespace std;
    int main(void)
    string s;
    char buffer[256];
    istringstream is1("0123456789");
    is1 >> setw(4) >> s;
    is1 >> setw(4) >> buffer;

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

    return 0;
    Matthew David Hills, Sep 5, 2003
    1. Advertisements

  2. 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 Harrison, Sep 5, 2003
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.