The MagPi Issue 18

Page 41

i nStr >> d_val ue; // Col l ect a doubl e val ue i nStr. seekg(0); // Reset the stri ng to be re- read i nStr >> i _val ue; // Col l ect an i nt val ue std: : cout << " Second Stri ng Stream: " << std: : endl ; std: : cout << " d_val ue=" << d_val ue << std: : endl ; std: : cout << " i _val ue=" << i _val ue << std: : endl << std: : endl ; }

return 0;

In this example, an input string stream is used to convert a string to a double and an integer value. At the start of the program, a double and an integer variable are declared. Then two strings are instantiated and assigned two strings. The first string contains a string representation of a double number, whereas the second string contains the string representation of an integer number. A trailing space is needed to delimit the number from the end of the string. The next step is the instantiation of an input stream called i nStr . When the i nStr stream is instantiated, the string str1 is assigned to it. Once a string stream is associated with a string, it can be used in the same way as other streams. The string value that is in the string associated with i nStr is then read once as a double value and once as an integer value. In between the two stream read operations, the seekg() function is used to rewind the position in the stream to the start of the stream. The two numerical values are then printed on the screen. In the second part of the program, the input string stream is assigned the second string. Then it is also read as an integer and as a double value. The program converts the string to the appropriate number type, without the need to explicitly state the type needed. Stream states and error bits

If an input string cannot be converted into the form requested the fai l bi t will be set. This could happen if a program is given a dictionary word rather than a number, or the number given is too large for the type requested. #i ncl ude <sstream> #i ncl ude <i ostream> #i ncl ude <stri ng> i nt strToLong(const std: : stri ng &i nputStri ng, l ong &l _val ue) { l ong l ongVal ue; std: : i stri ngstream i nStr(i nputStri ng); i nStr >> l _val ue; i f ((i nStr. rdstate() & std: : i os_base: : fai l bi t) > 0) return 1; return 0; } i nt strToDoubl e(const std: : stri ng &i nputStri ng, doubl e &d_val ue) { doubl e doubl eVal ue; std: : i stri ngstream i nStr(i nputStri ng); i nStr >> d_val ue; i f ((i nStr. rdstate() & std: : i os_base: : fai l bi t) > 0) return 1; return 0; }

41


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.