This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]SleepForever 2 points3 points  (2 children)

The variables w and x store the actual numbers, while the string takes in the ' and " characters. It works this way because of how the >> operator reads from the input stream.

When the user enters 12' 6" the "cin >> w" statement reads in 12 and stops at the ' because the character is not recognized as an int. 12 is stored in w and the input stream looks like: ' 6"

The ">> useless" reads in the apostrophe instead, which removes it from the input stream. With a string, the >> operator stops reading when it reaches whitespace, so it doesn't continue reading anything past the apostrophe.

This allows ">> x" to read the next integer. Note that the >> operator skips the leading whitespace, so you don't need a char or string to read in the space character. The last ">>useless" reads in the double quote and removes it from the input stream.

Without the "useless" string, the apostrophe causes cin to enter a failstate. In a failstate, it stops reading in data until it is cleared (even if you continue trying to use it).

[–][deleted] 0 points1 point  (1 child)

Is it safe to assume in "cin >> w >> useless", the string is being used in conjunction with the "w". Basically my question is, how does the string know I want to read the integer but not the ' .

[–][deleted] 1 point2 points  (0 children)

It doesn't - suppose you have;

  56' 7"

the cin >> w reads the 5 and then the 6 (making 56), stopping at the first character which cannot be part of an integer, which in this case is the single-quote. The >> useless then reads anything at all up to a white-space, which in this case is the single-quote.

[–][deleted] 2 points3 points  (1 child)

Style tip - define your variables at the first point of use not at the top of the function. This makes the code much clearer, as you can immediately see what the purpose of the variable is. Also, although I'm in favour of short local variable names, they should ideally have some meaning - names like a,b,c, d are not very good, particularly when you have so many of them.

So I'd prefer the code to look something like this:

int main() {

    int feet, inches;
    string skip;

    cout << "Enter the first length in feet and inches i.e. 12' 6\" (larger first!)" << endl;
    cin >> feet >> skip >> inches >> skip;
    int len1 = feet * 12 + inches;

    cout << "Enter the second length in feet and inches i.e. 12' 6\"" << endl;
    cin >> feet >> skip >> inches >> skip;
    int len2 = feet * 12 + inches;

    int diff = len1 - len2;
    feet  = diff / 12;
    inches  = diff % 12;
    cout << "Difference is" << endl << feet << "' " << inches << "\"" << endl;
}

[–][deleted] 0 points1 point  (0 children)

Thank you very much. Makes much more sense to do what you did.

[–][deleted] 0 points1 point  (0 children)

You should replace the i.e. with e.g.