Commit 841d4658 authored by GILLES Sebastien's avatar GILLES Sebastien
Browse files

Add an example of error handling for istringstream.

parent 98d2da42
......@@ -377,7 +377,7 @@
" int number = 657;\n",
" \n",
" std::ostringstream oconv; \n",
" oconv << \"The number is \" << number; \n",
" oconv << \"The number is \" << number;\n",
" std::cout << oconv.str() << std::endl;\n",
" \n",
" oconv.str(\"\"); // reset oconv\n",
......@@ -386,6 +386,37 @@
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Of course as for `std::cin` you may check the state of the object is still valid - if conversion is incorrect it won't!:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"#include <sstream> // for std::ostringstream and std::istringstream\n",
"#include <string>\n",
"\n",
"{\n",
" std::string number_as_string = \"abd\";\n",
" \n",
" int number;\n",
" \n",
" std::istringstream iconv(number_as_string);\n",
" iconv >> number; // invalid conversion!\n",
"\n",
" if (!iconv)\n",
" std::cerr << \"Invalid string!\" << std::endl;\n",
" else\n",
" std::cout << \"Number + 1 = \" << number + 1 << std::endl;\n",
"}"
]
},
{
"cell_type": "markdown",
"metadata": {},
......@@ -424,7 +455,7 @@
"{\n",
" std::string number_as_string = \"4557\";\n",
" \n",
" int number = stoi(number_as_string);\n",
" int number = std::stoi(number_as_string);\n",
" \n",
" std::cout << \"Number is \" << number << std::endl;\n",
"}"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment