avoids buffer overflow with cin.width
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
const int MAX = 20;
char str[MAX];
cout << "\nEnter a string: ";
cin >> setw(MAX) >> str;
cout << "You entered: " << str << endl;
return 0;
}
Character input with member function getline.
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.getline( buffer, SIZE );
cout << "\nThe sentence entered is:\n" << buffer << endl;
return 0;
}
cin and atoi, atof functions
#include <iostream.h>
#include <stdlib.h>
int main ()
{
char mybuffer [100];
float price;
int quantity;
cout << "Enter price: ";
cin.getline (mybuffer,100);
price = atof (mybuffer);
cout << "Enter quantity: ";
cin.getline (mybuffer,100);
quantity = atoi (mybuffer);
cout << "Total price: " << price*quantity;
return 0;
}
Enter price: 123
Enter quantity: 12
Total price: 1476"
cin Handles Different Data Types
#include <iostream>
using namespace std;
int main(void)
{
int myInt;
long myLong;
double myDouble;
float myFloat;
unsigned int myUnsigned;
cout << "int: ";
cin >> myInt;
cout << "Long: ";
cin >> myLong;
cout << "Double: ";
cin >> myDouble;
cout << "Float: ";
cin >> myFloat;
cout << "Unsigned: ";
cin >> myUnsigned;
cout << "\n\nInt:\t" << myInt << endl;
cout << "Long:\t" << myLong << endl;
cout << "Double:\t" << myDouble << endl;
cout << "Float:\t" << myFloat << endl;
cout << "Unsigned:\t" << myUnsigned << endl;
return 0;
}
cin with strings (cin.getline)
#include <iostream.h>
int main ()
{
char mybuffer [100];
cout << "What"s your name? ";
cin.getline (mybuffer,100);
cout << "Hello " << mybuffer << ".\n";
cout << "Which is your favourite team? ";
cin.getline (mybuffer,100);
cout << mybuffer;
return 0;
}
What"s your name? Joe
Hello Joe.
Which is your favourite team? Ea
Ea"
Concatenate put()
#include <iostream>
using namespace std;
int main()
{
cout.put("H").put("e").put("l").put("l").put("o").put("\n");
return 0;
}
Contrasting input of a string via cin and cin.get
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer1[ SIZE ];
char buffer2[ SIZE ];
cout << "Enter a sentence:" << endl;
cin >> buffer1;
cout << buffer1 << endl << endl;
cout << "Enter a sentence:" << endl;
cin.get( buffer2, SIZE );
cout << buffer2 << endl;
return 0;
}
Enter a sentence:
This is a sentence.
This
Enter a sentence:
is a sentence.
Contrasting input of a string with cin and cin.get.
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 80;
char buffer1[ SIZE ], buffer2[ SIZE ];
cout << "Enter a sentence:\n";
cin >> buffer1;
cout << "\nThe string read with cin was:\n"
<< buffer1 << "\n\n";
cin.get( buffer2, SIZE );
cout << "The string read with cin.get was:\n"
<< buffer2 << endl;
return 0;
}
Copy all standard input to standard output
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
int main ()
{
// copy all standard input to standard output
std::cout << std::cin.rdbuf();
}
asdf
asdf
asdf
asdf
fdsa
fdsa
Terminate batch job (Y/N)? n
Demonstrating member function width
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int widthValue = 4;
char sentence[ 10 ];
cout << "Enter a sentence:" << endl;
cin.width( 5 );
cin >> sentence;
cout << sentence << endl;
return 0;
}
Enter a sentence:
This is a sentence.
This
Extends std::streambuf to create data buffer
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <streambuf>
// for read():
#ifdef _MSC_VER
# include <io.h>
#else
# include <unistd.h>
#endif
class inbuf : public std::streambuf {
protected:
/* data buffer:
* - at most, four characters in putback area plus
* - at most, six characters in ordinary read buffer
*/
static const int bufferSize = 10; // size of the data buffer
char buffer[bufferSize]; // data buffer
public:
/* constructor
* - initialize empty data buffer
* - no putback area
* => force underflow()
*/
inbuf() {
setg (buffer+4, // beginning of putback area
buffer+4, // read position
buffer+4); // end position
}
protected:
// insert new characters into the buffer
virtual int_type underflow () {
// is read position before end of buffer?
if (gptr() < egptr()) {
return traits_type::to_int_type(*gptr());
}
/* process size of putback area
* - use number of characters read
* - but at most four
*/
int numPutback;
numPutback = gptr() - eback();
if (numPutback > 4) {
numPutback = 4;
}
/* copy up to four characters previously read into
* the putback buffer (area of first four characters)
*/
std::memmove (buffer+(4-numPutback), gptr()-numPutback,
numPutback);
// read new characters
int num;
num = read (0, buffer+4, bufferSize-4);
if (num <= 0) {
// ERROR or EOF
return EOF;
}
// reset buffer pointers
setg (buffer+(4-numPutback), // beginning of putback area
buffer+4, // read position
buffer+4+num); // end of buffer
// return next character
return traits_type::to_int_type(*gptr());
}
};
int main()
{
inbuf ib; // create special stream buffer
std::istream in(&ib); // initialize input stream with that buffer
char c;
for (int i=1; i<=20; i++) {
// read next character (out of the buffer)
in.get(c);
// print that character (and flush)
std::cout << c << std::flush;
// after eight characters, put two characters back into the stream
if (i == 8) {
in.unget();
in.unget();
}
}
std::cout << std::endl;
}
a
a
d
d
Is it a bad input
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main()
{
double area;
cout << "Please enter the area of a square: ";
cin >> area;
if (cin.fail())
{
cout << "Error: Bad input\n";
return 1;
}
if (area < 0)
{
cout << "Error: Negative area.\n";
return 1;
}
cout << "The side length is " << sqrt(area) << "\n";
return 0;
}
Manipulator that skips until end-of-line
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
#include <limits>
template <class charT, class traits>
inline
std::basic_istream<charT,traits>&
ignoreLine (std::basic_istream<charT,traits>& strm)
{
// skip until end-of-line
strm.ignore(std::numeric_limits<int>::max(),strm.widen("\n"));
// return stream for concatenation
return strm;
}
int main()
{
int i;
std::cout << "read int and ignore rest of the line" << std::endl;
std::cin >> i;
// ignore the rest of the line
std::cin >> ignoreLine;
std::cout << "int: " << i << std::endl;
std::cout << "read int and ignore two lines" << std::endl;
std::cin >> i;
// ignore two lines
std::cin >> ignoreLine >> ignoreLine;
std::cout << "int: " << i << std::endl;
}
read int and ignore rest of the line
123 qwe
int: 123
read int and ignore two lines
123wer
asdf
int: 123
Read a character from keyboard
/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
*
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
using namespace std;
int main()
{
char c;
// while it is possible to read a character
while (cin.get(c)) {
// print it
cout.put(c);
}
}
a
a
c
c
d
d
e
e
Terminate batch job (Y/N)? n
Read char array from keyboard, get its length and concatenate two strings
#include <iostream>
#include <string.h>
using std::cout;
using std::cin;
int main()
{
char firststring[40],secondstring[40],thirdstring[40];
int size;
cout << "Please enter a word \n";
cin.getline(firststring,40);
cout << "Please enter another word \n";
cin.getline(secondstring,40);
size = strlen(firststring);
strcat(firststring,secondstring);
cout << "The length of the first string you entered is" << size << "\n";
cout << "Both strings you entered are " << thirdstring<< "\n";
return 0;
}
Please enter a word
word
Please enter another word
word
The length of the first string you entered is4
Both strings you entered are ?
Read int value from keyboard
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a number: ";
int a; // declare one variable
cin >> a;
cout << "Enter a second number: ";
int b; // declare another variable
cin >> b;
cout << "Product: " << a*b << "\n";
return 0;
}
Enter a number: 123
Enter a second number: 12
Product: 1476
Testing error states.
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int integerValue;
// display results of cin functions
cout << "Before a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good();
cin >> integerValue;
cout << endl;
cout << "After a bad input operation:"
<< "\ncin.rdstate(): " << cin.rdstate()
<< "\n cin.eof(): " << cin.eof()
<< "\n cin.fail(): " << cin.fail()
<< "\n cin.bad(): " << cin.bad()
<< "\n cin.good(): " << cin.good() << endl << endl;
cin.clear();
cout << "After cin.clear()" << "\ncin.fail(): " << cin.fail()
<< "\ncin.good(): " << cin.good() << endl;
return 0;
}
Before a bad input operation:
cin.rdstate(): 0
cin.eof(): 0
cin.fail(): 0
cin.bad(): 0
cin.good(): 12
After a bad input operation:
cin.rdstate(): 0
cin.eof(): 0
cin.fail(): 0
cin.bad(): 0
cin.good(): 1
After cin.clear()
cin.fail(): 0
cin.good(): 1
Unformatted I/O using cin.read, cin.gcount and cout.write
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
const int SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:" << endl;
cin.read( buffer, 20 );
cout.write( buffer, cin.gcount() );
cout << endl;
return 0;
}
Enter a sentence:
This is a sentence.
This is a sentence.
Unformatted I/O with read, gcount and write.
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 80;
char buffer[ SIZE ];
cout << "Enter a sentence:\n";
cin.read( buffer, 20 );
cout << "\nThe sentence entered was:\n";
cout.write( buffer, cin.gcount() );
cout << endl;
return 0;
}
Use get() to read a string that contains spaces
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
char str[80];
cout << "Enter your name: ";
cin.get(str, 79);
cout << str << "\n";
return 0;
}
Enter your name: Joe
Joe
#include <iostream>
using namespace std;
#define INUMCHARS 45
#define INULL_CHARACTER 1
int main(void)
{
char pname[INUMCHARS + INULL_CHARACTER];
cout << "Please enter your first and last name: ";
cin.get(pname,INUMCHARS);
cout << "\n\nThank you, " << pname;
}
Using member functions get, put and eof.
#include <iostream>
using namespace std;
int main()
{
char c;
cout << "Before input, cin.eof() is " << cin.eof()
<< "\nEnter a sentence followed by end-of-file:\n";
while ( ( c = cin.get() ) != EOF )
cout.put( c );
cout << "\nEOF in this system is: " << c;
cout << "\nAfter input, cin.eof() is " << cin.eof() << endl;
return 0;
}
Using peek() and putback()
#include <iostream>
using namespace std;
int main()
{
char ch;
cout << "enter a phrase: ";
while ( cin.get(ch) )
{
if (ch == "!")
cin.putback("$");
else
cout << ch;
while (cin.peek() == "#")
cin.ignore(1,"#");
}
return 0;
}