Read Input Fiile String Firstname = Input.next();

C++ Tutorial - fstream: input and output

cplusplus_icon.png

Bookmark and Share




bogotobogo.com site search:


Stream

C++ provides methods of input and output through a mechanism known as streams.

Streams are a flexible and object-oriented arroyo to I/O. In this affiliate, we will run across how to utilize streams for data output and input. We will besides larn how to employ the stream mechanism to read from diverse sources and write to diverse destinations, such as the user console, files, and even strings.

In cout stream, we throw some variables down the stream, and they are written to the user's screen, or console. Streams vary in their direction and their associated source or destination.

For case, the cout stream is an output stream so its management is out. It writes data to the console so its associated destination is console. There is another standard stream chosen cin that accepts input from the user. Its direction is in, and its associated source is panel.

cout and cin are predefined instances of streams that are defined inside the std namespace in C++.

C++ uses type-safe I/O, that is, each I/O performance is executed in a manner sensitive to the data type. If an I/O member role has been defined to handle a detail information type, then that member function is called to handle that data type. If there is no match between the type of the actual data and a part for handling that data type, the compiler reports an error. Therefore, improper information cannot sneak through the system unlike in C, where assuasive for some subtle errors.

Users can specify how to perform I/O for objects of user-defined types by overloading the stream insertion operator (<<) and the stream extraction operator (>>). This extensi- bility is one of C++'s most valuable features.

cin & excedption

In the code beneath, the variable x is an integer but a character input is assigned to it. Though the default setting for exceptions() is goodbit, the overloaded exceptions(iostate) part gives united states of america control over how nosotros set the beliefs for the wrong input. The line cin.exceptions(ios::failbit) causes failbit to throw exception.

#include <iostream> #include <exception>  using namespace std;  int principal() { 	int 10;  	// make failbit to throw exception          cin.exceptions(ios::failbit);          try { 		cin >> x; 		cout << "input = " << ten << endl; 	} 	take hold of(ios_base::failure &fb;) { 		cout << "Exception:" << fb.what() << endl; 		cin.articulate(); 	}  	render 0; }        

Output may exist unlike depending on the implementation:

a Exception:ios_base::failbit set        

File Writing

<fstream> library provides functions for files, and we should simply add #include <fstream> directives at the start of our program.

To open a file, a filestream object should first be created. This is either an ofstream object for writing, or an ifstream object for reading.

The declaration of a filesream object for writing output begins with the ofstream, then a name for that filestream object followed by parentheses specifying the file to write to: ofstream object_name ("file_name");

#include <fstream> #include <cord> #include <iostream> using namespace std ;  int main() { 	string theNames = "Edsger Dijkstra: Made advances in algorithms, the semaphore (programming).\northward" ; 	theNames.append( "Donald Knuth: Wrote The Art of Computer Programming and created TeX.\due north" ) ; 	theNames.append( "Leslie Lamport: Formulated algorithms in distributed systems (e.thousand. the bakery algorithm).\due north") ;  	theNames.suspend( "Stephen Cook: Formalized the notion of NP-completeness.\n" ) ;          ofstream          ofs( "theNames.txt" ) ;  	if( ! ofs )	{ 		cout << "Mistake opening file for output" << endl ; 		return -1 ; 	} 	 	ofs << theNames << endl ; 	ofs.close() ; 	return 0 ; }        

With output equally below - theNames.txt:

Edsger Dijkstra: Fabricated advances in algorithms, the semaphore (programming). Donald Knuth: Wrote The Art of Calculator Programming and created TeX. Leslie Lamport: Formulated algorithms in distributed systems (e.g. the bakery algorithm). Stephen Cook: Formalized the notion of NP-abyss.        

ios

Tabular array

ios Description
ios::out Open a file to write output
ios::in Open a file to read input
ios::app Open a file to append at the end
ios::trunc Truncate the existing file (default)
ios::ate Open a file without truncating, and permit data to be written anywhere in the file.
ios::binary Treat the file every bit binary format rather than ASCII then that the data may exist stored in non-ASCII format.

When a filestream object is created, the parentheses post-obit its proper noun tin optionally contain boosted arguments. The arguments specify a range of file modes to control the beliefs of the filestream object. Since these file modes are part of the ios namespace, they must be explicitly addressed using that prefix as shown the tabular array above.

Several mides may be specified if they are separated by a pipe, "|". To open a file for binary output looks similar this:

ofstream object_name ("file_name", ios::out | ios::binary);        

The default behavior when no modes are specified considers the file every bit a text file that will exist truncated after writing. One of the well-nigh commonly used manner is ios::app, which ensures existing content will be appended when new output is written to the file.

File Reading

The ifstream object has a go() function that can be used to read a file. In the instance below, we read the input file one character at a time:

#include <string> #include <fstream> #include <iostream> using namespace std ;  int primary() {   char letter ;   int i ;   string line ;          ifstream          reader( "Shakespeare.txt" ) ;    if( ! reader ) {     cout << "Error opening input file" << endl ;     render -1 ;   }    for( i = 0; ! reader.eof() ; i++ ) {     reader.get( alphabetic character ) ;     cout << letter ;  	/*          getline( reader , line ) ;     cout << line << endl ; 	*/   }    reader.shut() ;      render 0 ; }        

Output is:

Macbeth: To-morrow, and to-morrow, and to-morrow, Creeps in this fiddling footstep from solar day to mean solar day, To the terminal syllable of recorded time; And all our yesterdays take lighted fools The manner to dusty decease. Out, out, cursory candle! Life's only a walking shadow, a poor role player, That struts and frets his hour upon the stage, And so is heard no more. It is a tale Told by an idiot, full of sound and fury, Signifying nothing.        

Similar to the higher up example, the following gets words from the Linux lexicon /usr/share/dict/words, and puts into a vector after filtering words that kickoff with lower example alphabetic character:

#include <iostream> #include <fstream> #include <cord> #include <vector>  using namespace std;  int main() {   string line;   vector            dictionary;            ifstream            dict_reader("/usr/share/dict/words");   if( !dict_reader ) {     cout << "Error opening input file - dict  " << endl ;     get out(1) ;   }    while(!dict_reader.eof()) {            getline(dict_reader,line);     if(line[0] >= 'a' && line[0] <= 'z')       dictionary.push_back(line);   }   for(int i = 0; i < dictionary.size(); i++) {     cout << lexicon[i] << " " << endl;   } }                  

The output is:

a a' a- a. a1 aa aaa ... zythum zyzzyva zyzzyvas zZt        

The fstream::eof() may non piece of work under certain conditions, so sometimes nosotros may want the following lines:

          // while(!dict_reader.eof()) {  //   getline(dict_reader,line);  =>     while(getline(dict_reader,line)) {        

The getline() can have additional argument for a delimiter where to end reading. This tin be used to read in tabulated information:

Tommy	Tutone	San Francisco	401-867-5309 Celine	Dion	Lava Canada	450-978-9555  LA	Times	Los Engeles	800-252-9141        

Each detail in the recode above is separated by tab and line feed. The following code reads in the data and prints out each particular in a line.

#include <fstream> #include <iostream> #include <string> using namespace std;  int master() { 	const int RECORDS = 12; 	ifstream reader("PhoneBook.txt"); 	if(!reader) { 		cout << "Error: cannot open input file" << endl; 		render -1; 	} 	string item[RECORDS]; 	int i = 0; 	while(!reader.eof()) { 		if((i+1) % 4 == 0)  			getline(reader,item[i++],'\n'); 		else 			getline(reader,particular[i++],'\t'); 	} 	i = 0; 	while(i < RECORDS) { 		cout << "First name " << item[i++] << endl; 		cout << "Final name " << item[i++] << endl; 		cout << "Area " << item[i++] << endl; 		cout << "Phone " << item[i++] << endl << endl; 	} 	reader.close(); 	return 0; }        

Output:

First proper noun Tommy Last proper noun Tutone Area San Francisco Phone 401-867-5309  Kickoff proper noun Celine Last proper noun Dion Area Lava Canada Phone 450-978-9555  Offset name LA Terminal name Times Area Los Engeles Phone 800-252-9141        

Reading in data to make full a vector - A

The following case reads in int data from a file, and so fills in vector. If the infinite is non enough to hold the information, the vector resizing information technology past x.

#include <iostream> #include          <fstream>          #include <vector>  using namespace std;  int master() {   // vector with 10 elements   std::vector<int>v(10);    // ifp: input file pointer   std::ifstream ifp("data", ios::in);    int i = 0;   while(!ifp.eof())   {     ifp >> v[i++];     if(i % nine == 0) v.resize(five.size() + x);   }    std::vector<int>::iterator it;   for(it = v.begin(); it != v.end(); ++it )    std:: cout << *it << ' ';   std::cout << endl; }        

The input file looks similar this:

1 two three iv 5 six 7 8 9 10 11 12 xiii fourteen 15 16 17 18 19 xx 21 22 22 24 25        

Output:

1 two 3 4 5 vi seven 8 9 10 11 12 xiii 14 15 16 17 18 19 20 21 22 22 24 25 0 0 0 0 0        

Reading in information to fill up a vector - B

The post-obit example is almost the same as the previous example: information technology reads in string data from a file and fills in vector.

The std::istreamstd::ctype_base::space is the default delimiter which makes it finish reading farther grapheme from the source when it sees whitespace or newline.

As we tin meet from the data file (names) we're using:

Mao Asada Carolina Kostner Ashley Wagner Gracie Gilded Akiko Suzuki Kanako Murakami Adelina Sotnikova Kaetlyn Osmond Yuna Kim Julia Lipnitskaia        

as an input. When we reads in the data, it stores first_name and last name into the vector. But we want to treat them equally a pair. And then, nosotros subsequently put the pair into a map.

Here is the code:

/* w.cpp */ #include <iostream> #include <fstream> #include <string> #include <vector> #include <map>  using namespace std;  int read_words(vector<string>& words, ifstream& in) {   int i = 0;   while(!in.eof())     in >> words[i++];   return i-one; }  int principal() {   ifstream ifp("names");    vector<string> w(500);   int number_of_words = read_words(w, ifp);   w.resize(number_of_words);    for(auto it : w)     cout << information technology << " ";   cout << endl;    map<string, string> wMap;    for(int i = 0; i  <  number_of_words;) {     wMap.insert(pair<string, cord>(westward[i], w[i+1]));     i += ii;   }    cout << "wMap.size()=" << wMap.size() << endl;   for(auto it = wMap.begin(); it != wMap.end(); it++)     cout <<  it->commencement << " " << it->second << endl; }        

Output:

wMap.size()=ten Adelina Sotnikova Akiko Suzuki Ashley Wagner Carolina Kostner Gracie Aureate Julia Lipnitskaia Kaetlyn Osmond Kanako Murakami Mao Asada Yuna Kim        

Note that nosotros're using C++11 motorcar keyword that can deduce the type from context, we should let the compiler know we want the file compiled with C++11:

chiliad++          -std=c++11          -o west w.cpp        

Alignment and field width - Russian Peasant Multiplication

Here is an case that shows output of three integers with field width 5 and left aligned.

// Russian Peasant Multiplication   #include <iostream> #include <iomanip> using namespace std;  int RussianPeasant(int a, int b) { 	int 10 = a,  y = b; 	int val = 0; 	cout << left << setw(five) << x << left << setw(5) << y << left << setw(5) << val << endl; 	while (x > 0) { 		if (x % 2 == 1) val = val + y; 		y = y << one;  // double 		x = ten >> 1;  // half 		cout << left << setw(v) << 10 << left << setw(5) << y << left << setw(five) << val << endl;  	} 	return val; }  int main() { 	RussianPeasant(238, 13); 	return 0; }        

The output should look like this:

238  13   0          119          26          0          59          52          26          29          104          78 xiv   208  182          7          416          182          iii          832          598          ane          1664          1430 0    3328          3094        

Really, the multiplication is known as Russian Peasant Multiplication. Whenever x is odd, the value of y is added to val until x equals to zero, and and so it returns 3094 .

Retasting C file IO - fseek

What would be the output from the code below.

#include<stdio.h>  int main() {     FILE *fp;     char c[1024];     fp = fopen("examination.txt", "r");  // "Kernighan and Ritchie"      c[0] = getc(fp);              // c[0] = K     fseek(fp, 0, SEEK_END);       // file position moved to the end     fseek(fp, -7L, SEEK_CUR);     // 7th from the finish, with is 'R' of "Ritchie"     fgets(c, half-dozen, fp);              // read 6-1 characters from 'R'     puts(c);                      // "Ritch"     return 0; }        

Retasting C file IO - fgets

Q: In a file contains the line "The C Programming Language\r\n".
This reads this line into the assortment southward using fgets().
What will southward contain?

Ans: "The C Programming Language\r\0"

That'southward because char *fgets(char *due south, int n, FILE *stream) reads characters from stream into the string due south.
It stops when it reads either due north - 1 characters or a newline character, whichever comes first.
Therefore, the string str contains "The C Programming Language\r\0".

Retasting C file IO - scanf

scanf() returns the number of items of the argument list successfully filled. In the lawmaking below, though 99 is given, the out is 1 because scanf() returns the number of input which is one.

#include <stdio.h>  int primary() {     int i;     /* 99 is given for the input */     printf("%d\due north", scanf("%d", &i;));  /* Though i = 99, print output is 1 */     render 0; }        

argc/argv

int chief(int argc, char *argv[]){}        
  1. argc volition have been set up to the count of the number of strings that
  2. argv will signal to, and argv will take been set to point to an array of pointers to the private strings
  3. argv[0] volition point to the program name cord, what ever that is,
  4. argv[one] will point to the first argument string,
  5. argv[ii] will point to the 2nd argument cord, and so on, with
  6. argv[argc-one] pointing to the last argument cord, and
  7. argv[argc] pointing at a Naught arrow

ethertonleat1970.blogspot.com

Source: https://www.bogotobogo.com/cplusplus/fstream_input_output.php

0 Response to "Read Input Fiile String Firstname = Input.next();"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel