133k views
4 votes
Java ZyBooks:

CHALLENGE ACTIVITY
9.3.2: Reading from a string.
Write code that uses the input string stream inSS to read input data from string userInput, and updates variables userMonth, userDate, and userYear. Sample output if the input is "Jan 12 1992":
Month: Jan
Date: 12
Year: 1992

User Deepblue
by
6.9k points

1 Answer

5 votes

Answer:#include <iostream>

#include <sstream>

#include <string>

using namespace std;

int main() {

string userInput = "Jan 12 1992";

istringstream inSS(userInput);

string monthStr;

int dateInt, yearInt;

inSS >> monthStr >> dateInt >> yearInt;

userMonth = monthStr;

userDate = dateInt;

userYear = yearInt;

cout << "Month: " << userMonth << endl;

cout << "Date: " << userDate << endl;

cout << "Year: " << userYear << endl;

return 0;

}

Explanation:The code initializes an input string stream inSS with the string userInput. It then declares three variables monthStr, dateInt, and yearInt to store the input values for the month, date, and year respectively.

The inSS object is used to extract data from the string using the stream operator >>. The first value is read into monthStr, which is a string. The second value is read into dateInt, which is an integer. The third value is read into yearInt, which is also an integer.

Finally, the values of userMonth, userDate, and userYear are updated with the values read from the input stream, and the values are printed to the console. The output should match the sample output provided in the question.

User Jeff Maner
by
7.2k points