GettingInput

advertisement
CSC221 Data Structures
Fall 2007
Burg
Getting Input
You would expect that getting input from a file or from the keyboard
ought to be easy, but sometimes it seems to be the thing that trips
students up the most. So here’s some information about functions and
operators for getting input.
Extraction from an input stream using >>
cin >> n;
n
can be any base type, or a pointer to char (for string input). Whitespace characters
(blank, newline, tab) are ignored if they precede input, and the first whitespace character
after the input is used a stopper. That is, it is not read but is left for the next attempted
input. Extractions can be chained:
cin >> n >> p >> q;
If you want to get a single character, including whitespace characters, you can use the get
function.
cin.get(c);
http://www.cplusplus.com/reference/iostream/istream/get.html
istream::get
int get();
istream& get
istream& get
istream& get
istream& get
istream& get
(
(
(
(
(
public member function
char& c );
char* s, streamsize n );
char* s, streamsize n, char delim );
streambuf& sb);
streambuf& sb, char delim );
Get unformatted data from stream
These member functions perform unformatted input operations. Depending on the type
and number of arguments the function behaves in the following way:
int get();
Extracts a character from the stream and returns its value (casted to an integer).
istream& get ( char& c );
Extracts a character from the stream and stores it in c.
istream& get (char* s, streamsize n );
Extracts characters from the stream and stores them as a c-string into the array
beginning at s. Characters are extracted until either (n - 1) characters have been
extracted or the delimiting character '\n' is found. The extraction also stops if
the end of file is reached in the input sequence or if an error occurs during the
input operation.
If the delimiting character is found, it is not extracted from the input sequence
and remains as the next character to be extracted. Use getline if you want this
character to be extracted (and discarded).
The ending null character that signals the end of a c-string is automatically
appended at the end of the content stored in s.
istream& get (char* s, streamsize n, char delim );
Same as above, except that the delimiting character is the one specified indelim
instead of '\n'.
istream& get (streambuf& sb);
Extracts characters from the stream and inserts them in the stream buffer sb until
either the delimiting character '\n' is found or end of file is reached. The
extraction also stops if an error occurs either in the input sequence controled by
the stream or in the output sequence controlled by sb.
istream& get (streambuf& sb, char delim );
Same as above, except that the delimiting character is the one specified indelim
instead of '\n'.
The number of characters read by any of the previous input operations can be obtained by
calling to the member function gcount.
Parameters
c
A char variable to store the extracted character.
s
A pointer to an array of characters where the string is stored as a c-string
n
Maximum number of characters to store (including the ternimating null
character).
This is an integer value of type streamsize.
delim
The delimiting character. The operation of extracting succesive characters is
stopped when this character is read. This parameter is optional, if not specified the
function considers '\n' (a newline character) to be the delimiting character.
sb
An output stream buffer (an object of class streambuf or any of its derived
classes).
Return Value
For the first prototype, the function returns the character read. For the remaining
prototypes, the function return *this.
Errors are signaled by modifying the internal state flags:
flag
error
eofbit The end of the source of characters is reached during its operations.
No characters were extracted because either the end was prematurely found or
the insertion operation in the destination failed (this only applies to the
failbit
streambuf case).
Notice that some eofbit cases will also set failbit.
badbit An error other than the above happened.
Additionaly, in any of these cases, if the appropriate flag has been set with member
function ios::exceptions, an exception of type ios_base::failure is thrown.
Example
// istream get
#include <iostream>
#include <fstream>
using namespace std;
int main () {
char c, str[256];
ifstream is;
cout << "Enter the name of an existing text file: ";
cin.get (str,256);
is.open (str);
// open file
while (is.good())
{
c = is.get();
cout << c;
}
// loop while extraction from file is possible
is.close();
// close file
return 0;
}
// get character from file
This example prompts for the name of an existing text file and prints its content on the
screen.
Basic template member declarations
( basic_istream<charT,traits> )
typedef charT char_type;
int_type get();
basic_istream& get (char_type& c );
basic_istream& get (char_type* s, streamsize n );
basic_istream& get (char_type* s, streamsize n, char_type delim );
basic_istream& get (basic_streambuf<char_type,traits>& sb);
basic_istream& get (basic_streambuf<char_type,traits>& sb, char_type
delim );
http://www.cppreference.com/cppstring/getline.html
istream getline(istream &, string &,
char delimiter)
function
Syntax:
#include <string>
istream& getline( istream& is, string& s, char delimiter = '\n' );
The C++ string class defines the global function getline() to read strings from an I/O
stream. The getline() function, which is not part of the string class, reads a line from is
and stores it into s. If a character delimiter is specified, then getline() will use delimiter to
decide when to stop reading data.
For example, the following code reads a line of text from stdin and displays it to stdout:
string s;
getline( cin, s );
cout << "You entered " << s << endl;
After getting a line of data in a string, you may find that string streams are useful in
extracting data from that string. For example, the following code reads numbers from
standard input, ignoring any "commented" lines that begin with double slashes:
// expects either space-delimited numbers or lines that start with
// two forward slashes (//)
string s;
while( getline(cin,s) ) {
if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) {
cout << " ignoring comment: " << s << endl;
} else {
istringstream ss(s);
double d;
while( ss >> d ) {
cout << "
got a number: " << d << endl;
}
}
}
When run with a user supplying input, the above code might produce this output:
// test
ignoring comment: // test
23.3 -1 3.14159
got a number: 23.3
got a number: -1
got a number: 3.14159
// next batch
ignoring comment: // next batch
1 2 3 4 5
got a number: 1
got a number: 2
got a number: 3
got a number: 4
got a number: 5
50
got a number: 50
From http://www.cplusplus.com/reference/clibrary/cstdio/getchar.html
getchar
int getchar ( void );
function
<cstdio>
Get character from stdin
Returns the next character from the standard input (stdin).
It is equivalent to getc with stdin as its argument.
Parameters
(none)
Return Value
The character read is returned as an int value.
If the End Of File is reached or a reading error happens, the function returns EOF and the
corresponding error or eof indicator is set. You can use either ferror or feof to determine
whether an error happened or the End-Of-File was reached.
Example
/* getchar example : typewriter */
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
A simple typewriter. Every sentence is echoed once ENTER has been pressed until a dot
(.) is included in the text.
http://www.cplusplus.com/reference/clibrary/cstdio/getc.html
getc
int getc ( FILE * stream );
function
<cstdio>
Get character from stream
Returns the character currently pointed by the internal file position indicator of the
specified stream. The internal file position indicator is then advanced by one character to
point to the next character.
getc is equivalent to fgetc and also expects a stream as parameter, but getc may be
implemented as a macro, so the argument passed to it should not be an expression with
potential side effects.
See getchar for a similar function without stream parameter.
Parameters
stream
pointer to a FILE object that identifies the stream on which the operation is to be
performed.
Return Value
The character read is returned as an int value.
If the End-of-File is reached or a reading error happens, the function returns EOF and the
corresponding error or eof indicator is set. You can use either ferror or feof to determine
whether an error happened or the End-Of-File was reached.
Example
/* getc example: money counter */
#include <stdio.h>
int main ()
{
FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
do {
c = getc (pFile);
if (c == '$') n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d$.\n",n);
}
return 0;
}
This program reads an existing file called myfile.txt character by character and uses
the n variable to count how many dollar characters ($) does the file contain.
http://www.cplusplus.com/reference/clibrary/cstdio/fgetc.html
fgetc
int fgetc ( FILE * stream );
function
<cstdio>
Get character from stream
Returns the character currently pointed by the internal file position indicator of the
specified stream. The internal file position indicator is then advanced by one character to
point to the next character.
fgetc and getc are equivalent, except that the latter one may be implemented as a
macro.
Parameters
stream
Pointer to a FILE object that identifies the stream on which the operation is to be
performed.
Return Value
The character read is returned as an int value.
If the End-of-File is reached or a reading error happens, the function returns EOF and the
corresponding error or eof indicator is set. You can use either ferror or feof to determine
whether an error happened or the End-Of-File was reached.
Example
/* fgetc example: money counter */
#include <stdio.h>
int main ()
{
FILE * pFile;
int c;
int n = 0;
pFile=fopen ("myfile.txt","r");
if (pFile==NULL) perror ("Error opening file");
else
{
do {
c = fgetc (pFile);
if (c == '$') n++;
} while (c != EOF);
fclose (pFile);
printf ("File contains %d$.\n",n);
}
return 0;
}
This program reads an existing file called myfile.txt character by character and uses
the n variable to count how many dollar characters ($) does the file contain.
Download