Sometimes text contains values you want to calculate with. std::istringstream reads formatted values from a string already held in memory. Include <sstream> to use it. This program does not wait for keyboard input or read a file.
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::istringstream source("Pens 6");
std::string item = "";
int quantity = 0;
if (source >> item >> quantity) {
std::cout << item << ": " << quantity << '\n';
} else {
std::cout << "Could not read the record\n";
}
return 0;
}
The declaration constructs source with the prefilled text. The extraction operator >> takes the next formatted value from that stream and stores it in the variable on its right. Extraction skips leading whitespace. Reading into a string this way takes one word; reading into an integer interprets numeric text as a number.
Read the chain from left to right: first fill item, then fill quantity. The stream keeps track of where it has reached, so the second extraction continues after the first word. In the if condition, the chain also checks whether both reads succeeded. If the quantity is missing or is not readable as an integer, the program takes the else path rather than reporting a complete record.
Your editor holds "Notebooks 8", an empty item name, and a zero quantity. The success and failure branches are already supplied. Replace only the placeholder condition with the extraction chain. On success, the existing statement displays the word and the numeric quantity. The supplied record has a one-word item followed by an integer; this is not a way to split an arbitrary sentence.
Successful extraction means those two values were readable, not that the entire record was validated. Extra text after the integer can remain unread, and a readable negative quantity is still an integer. Checking for leftover text or enforcing a nonnegative quantity would be separate validation steps. Use the fields as a complete record only inside the success branch: if the second read fails, the first may already have changed item.
false with a stream extraction chain that reads item and then quantity from record. Expect Order: Notebooks 8.Edit main.cpp, press Run to inspect the Console, then Submit to check your work.