-
Convert stdin string input to an integer using cin
#include <iostream> #include <limits> using namespace std; int main () { int i; cout << "Enter an integer: "; cout.flush(); while ( (cin >> i).fail() ) { // Clear the error flag in the cin object cin.clear(); // Discard the erroneous user input cin.ignore(numeric_limits<streamsize>::max(), 'n'); cout << "Please try again: "; cout.flush(); } cout << "The integer value is: " << i; }
-
Convert a string to an integer using a stringstream
Using a const char*
#include <sstream> #include <iostream> //used for cout int main() { const char* str = "12345"; std::stringstream ss( str ); int i; ss >> i; if (ss.fail()) { // Error } else { std::cout << "The integer value is: " << i; } return 0; }
-
Convert a string to an integer using the boost lexical_cast
#include <boost/lexical_cast.hpp> #include <string> int main() { std::string str = "12345"; int i; try { i = boost::lexical_cast<int>(str); } catch( const boost::bad_lexical_cast & ) { //unable to convert } return 0; }
-
Convert a string to an integer using atoi
int atoi ( const char * str );Getting input from keyboard (
stdin)
#include <stdio.h> #include <stdlib.h> int main () { int i; char str[256]; printf ("Enter a number: "); fgets ( str, 256, stdin ); i = atoi (str); printf ("The integer value is: %d.",i); return 0; }
Using a
const char*
#include <stdio.h> #include <stdlib.h> int main () { const char* str = "12345"; int i = atoi(str); printf ("The integer value is: %d.",i); return 0; }
-
Embed PHP into HTML
PHP code can be embedded into any HTML web page by using the
<?php ?>tags.<html> <head> <title>My PHP Page</title> </head> <body> <?php echo "Hello World!"; ?> </body> </html>
Most web servers will only interpret php code in pages with a
.phpfile extension. -
For loop
This is an example of a typical for loop.
for( int var=0; var<10; var++) { // Code to execute }
The initiation of the for loop includes three different command seperated be semicolons.
First
In this example an integer namedvaris created and initialized to;
If we are using a variable that has already being instantiated just enter the name of the variable and optionally assign it a new value.
ie.
int var = 0; for(var=2; var<10; var++) { // Code to execute }
