C++ File Processing

String


One of the most useful data types is the string. A string can hold multiple characters.
To use the string, you must use the <string> header file.

#include <iostream>
#include <string>
using namespace std;

int main ()
{
string user_name;
cout << “Please enter your name: “;
cin >> user_name;
cout << “Hi ” << user_name << “\n”;
}


appending : put two strings togther 

string user_full_name = user_first_name + ” ” + user_last_name;

To use getline, you pass in a source of input, in this case cin, the string to read into, and a character
on which to terminate input. For example, the following code reads the user’s first name:
getline( cin, user_first_name, ‘\n’ );

--------------------------------------------------

cin >> target : skips whitespace, then gets a number, word, or character

—————————————————

The getline function reads an entire line from a stream, up to and including the next newline character. It takes three parameters :

getline( cin, user_first_name, ‘\n’ );

cin >> ws      : skips whitespace (spaces, tabs, and newlines)

cout << "First Name: ";
cin >> ws;

cin.getline(FirstName, 20);

Inputting this:
1     Jose Goncalves
2 // Note the whitespaces at the start

Would thus return
1 Jose Goncalves
2 // Note that the whitespace in the middle is still there.

——————————————–

#include <iostream>
#include <fstream>
#include <string>

 int main () {

string str;
ifstream ifs(“d:\file.txt”);
getline (ifs,str);
cout << “first line of the file is ” << str << “.\n”;
system(“PAUSE”);

}

——————————————-

// getline with strings

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile (“d:\c.txt”);
int i = 0 ;

if (myfile.is_open())
{
while ( myfile.good() )
{
i++ ;
getline (myfile,line);
cout << i << ” ” << line << endl;
}
myfile.close();
}
else cout << “Unable to open file”;
system(“PAUSE”);
return 0;
}

Leave a comment