stringstream

Requires #include <sstream> ; preprocessor directive.

 

Enables string based objects to be treated as a stream, thus allowing extraction/insertion to/from strings.

 

Useful for converting strings to numbers and vice-versa.

 

 

String objects (being acquired via getline() function) are converted to numerical values:

#include <iostream>
#include <string>
#include<sstream>
using namespace std;

int main () {

	string myString ;

	int laps = 0 ;

	float time = 0 ;

	cout << "Please enter the number of laps completed:" << endl ;

	getline(cin, myString) ;

	stringstream(myString) >> laps ;

	cout << "Please enter the time taken to complete those laps:" << endl ;

	getline(cin, myString) ;

	stringstream(myString) >> time ;

	cout << "Average lap speed was: " << time / laps << endl ;

	return 0;
}

Compile & Run:

Please enter the number of laps completed:
28
Please enter the time taken to complete those laps:
345
Average lap speed was: 12.3214

Leave a Reply