Cin.width Problem?

Cin.width is not limiting the number of characters read from a string. Any explanation why it isn't working? I want to take the users name, but only store the first 7 letters (only first name) of their name.

1
2
3
cout << setw(INPUT_WIDTH) << "Please enter your name: ";
cin.width(7);
getline(cin, name);
> I want to take the users name, but only store the first 7 letters (only first name) of their name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <iomanip>

int main()
{
    const int width = 7 ;

    std::string name ;

    std::cout << "first name (first " << width << " characters are significant)? " ;

    // formatted input: reads up to the first white-space character
    // or till 'width' (seven) non-whitespace characters have been read
    std::cin >> std::setw(width) >> name ;
    std::cout << name ;

    std::cin.ignore( 1000, '\n' ) ; // throw away the remaining characters in the line
}

Last edited on
Thank you for the reply -- I wasn't particularly looking for a fix, but more so of an explanation as to why mine doesn't work.

Sorry I didn't include all of my code, I was just curious about this one portion.

EDIT** - Believe I resolved it. cin.width is not compatible with strings, only cstrings. I tried multiple times with strings, then used a c-string followed by an cin.ignore and it worked perfectly.
Last edited on
cin.width is not compatible with strings, only cstrings
Wrong. JLBorges solution uses strings and works fine.
All format specifiers work only with formatted input and does not work with unformatted input.
std::getline is unformatted input, so it does not work with width.
operator>> is formtted input, so it works fine with format specifiers.
There is another version of getline for c-strings, which, because of char buffers inherent problem, has to provide maximum length specifier to avoid buffer overflow.
Topic archived. No new replies allowed.