Home  >  Article  >  Backend Development  >  Why Does `stringstream` Modify the Target Variable on Extraction Failure in C 11 and Later?

Why Does `stringstream` Modify the Target Variable on Extraction Failure in C 11 and Later?

Barbara Streisand
Barbara StreisandOriginal
2024-11-26 15:46:09469browse

Why Does `stringstream` Modify the Target Variable on Extraction Failure in C  11 and Later?

Why Does stringstream >> Alter Target Value on Extraction Failure After C 11?

Stroustrup's "TC PL" states that a target variable's value should remain unchanged if an istream or ostream operation fails. However, this contradicts observed behavior with stringstream:

#include <iostream>
#include <sstream>

int main() {
  std::stringstream ss;
  int v = 123;
  ss << "The quick brown fox.";
  if (ss >> v) {
    std::cout << "Unexpected success in reading a word into an int!\n";
  }
  std::cout << "After extraction failure: " << v << "\n";
  return 1;
}

This code prints "After extraction failure: 0," despite Stroustrup's claim.

C 11 Behavior Modification

This contradiction stems from a change in stringstream behavior after C 11. Before C 11, stringstream used a scanf-style parsing method, leaving the target value unchanged on failure. However, since C 11, it employs std::strtoll, which writes a zero to the value variable and sets failbit on extraction failure.

This change aligns with the revised C 11 behavior of istream and ostream operations:

  • On failure, the target value is set to 0 or the appropriate extreme value.
  • failbit is set to indicate the failure.

Conclusion

While Stroustrup's quote accurately describes the behavior of istream and ostream operations prior to C 11, stringstream's post-C 11 behavior deviates from this description due to the adoption of a different extraction mechanism. In C 11 and beyond, it's essential to be aware of this altered behavior when using stringstream operations.

The above is the detailed content of Why Does `stringstream` Modify the Target Variable on Extraction Failure in C 11 and Later?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn