getline

Strings in C++

The memory for a string is a sequence of consecutive bytes, each holding one character. The amount of memory reserved for a string variable is automatically increased or decreased to fit the the number of characters stored in the string as the program runs. We can use cin to read a value into a variable.

#include <iostream>
#include <string>

using namespace std;


int main(){

    char initial;
    string lastName;

    cout << "Enter the initial of your first name: ";
    cin >> initial;
    cout << "Please enter your last name: ";
    cin >> lastName;
    cout << "Hello, " << initial << ". " << lastName << endl;

    return 0;

}

Note that when we include a string literal directly in code we must enclose it in double quotes. Single characters should be enclosed in single quotes as well.

When cin is used to read input from the terminal it skips over any leading whitespace, and then stops reading new characters into the string when it encounters whitespace. What this means is that we cannot use cin >> to read a string with more than one word in it.

The + operator will concatenate, or join, string or character values. It should be noted that the + operator is the same as the one used in arithmetic; while this seems natural enough to us humans, the computer is actually clued into this explicitly through what is known as operator overloading. We will look at operator overloading in greater detail in future lessons.

#include <iostream>
#include <string>

using namespace std;


int main(){

    string firstName;
    string lastName;
    string fullName;
    
    cout << "Please enter your first name: ";
    cin >> firstName;
    
    cout << "Please enter your last name: ";
    cin >> lastName;
    
    fullName = firstName + " " + lastName;
    
    cout << fullName;

    return 0;

}

We can determine the length of a string variable by using the length() function. We do this by using the dot notation, as seen below.

#include <iostream>
#include <string>

using namespace std;


int main(){

    string s = "27 A Wimpole Street";
    
    int a = s.length();
    
    cout << "The length of the string [" << s << ']' << endl;
    cout << "is " << a << endl;

    return 0;

}

The setw manipulator is used to control horizontal alignment of output; it is found in the iomanip library. We specify the width in terms of number of characters using an integer value.

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;


int main(){

    string str = "Alar";
    cout << setw(10) << "Carcosa" << endl;
    cout << setw(10) << str << endl;
    cout << setw(20) << "Hastur" << endl;

    return 0;

}

The setw manipulator is often used to more effectively align output in columns.

In our next example we will accept input from the user and put this data into a file.

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

using namespace std;


int main(){

    const double WAGE = 11.15;
    int workers;
    int hours;
    string name;
    
    ofstream fout("wage_data.txt");
    
    cout << "How many workers worked this week?\t";
    cin >> workers;
    
    
    fout << "Name" << setw(20) << "Hours" << setw(15) << "Pay" << endl;
    fout << fixed << showpoint << setprecision(2);
    
    for(int worker=1; worker<=workers; worker++){
        cout << "Worker's last name: ";
        cin >> name;
        cout << "Hours worked: ";
        cin >> hours;
        fout << name << setw(244-name.length()) << hours << setw(15) << hours * WAGE << endl;
    }
    return 0;

}

It’s worth noting here that cin and cout are both streams. A stream is a sequence of data that comes from a particular source and is sent to a particular destination. The cin stream comes from the keyboard, where it is held in cin’s buffer until they are sent to a program’s variables for storage. For cout, data is moved from the program to the screen.

We should also reiterate here that cin does not discard the trailing newline, which is to say the Enter key that is pressed in order to send the data to cin. Likewise, cin ignores whitespace that precedes the string data being input. This all works well together as long as we are only entering in single words, but what if we want to input entire sentences? In that case, we can use the getline() function.

#include <iostream>
#include <string>

using namespace std;


int main(){

    string s;
    
    for(int i = 0; i < 5; i++){
        cout << "Please enter a string: " << endl;
        getline(cin, s);
        cout << "That string has " << s.length() << " characters" << endl;
    }
    return 0;

}

We can use the ignore() function to skip over any trailing end-of-line characters that might still be in the buffer. The ignore() function can take two arguments, the first being the maximum number of characters it should possibly read, and the second being the character that when reached will cause the ignore() function to stop reading characters from standard input early.

#include <iostream>
#include <string>
#include <iomanip>
#include <limits>

using namespace std;


int main(){

    int age;
    int number;
    
    string name;
    string hometown;
    
    cout << "Enter your age: ";
    cin >> age;
    
    cin.ignore(64, '\n');
    
    cout << "Enter your name: ";
    getline(cin, name);
    
    cout << "Enter your favorite number: ";
    cin >> number;

    //must include limits header file
    cin.ignore(numeric_limits<streamsize>::max(),'\n');
    
    cout << "Enter your hometown: ";
    getline(cin, hometown);
    

    cout << setw(10) << "name:" << name << endl;
    cout << setw(10) << "hometown:" << hometown << endl;
    cout << setw(10) << "age:" << age << endl;
    cout << setw(10) << "number:" << number << endl;
    
    return 0;

}

Basic Input Functions in C++

There are numerous potential sources of error when we request user input. In addition, these errors can cascade down from our program if there is additional code to read more data from the input stream.

A simple technique to avoid cascading errors is flushing the input stream using the ignore() function. The ignore() function reads and discards characters obtained from input.

#include <iostream>

#define MAXCHAR 100

using namespace std;

int main(void){
    
    int value;
    char ch;
    
    cout << "Please enter a number and a letter." << endl;
    cin >> value >> ch;
    cout << ch << value << endl;
    
    cin.ignore(MAXCHAR, '\n');
    
    cout << "Please enter a number and a letter." << endl;
    cin >> value >> ch;
    cout << ch << value endl;
    
    return 0;
}

Character strings can be read in using the getline() function. The getline() function accepts three arguments, the first argument is a char array, the second argument is the length specified as an integer, and the third argument is a delimeter character.

#include <iostream>

#define BUFFER 512

using namespace std;

int main(void){
    
    char charBuffer[BUFFER];
    
    cout << "Please enter a string of text and press Enter" << endl;
    
    cin.getline(charBuffer, BUFFER, '\n');
    
    cout << "You entered: ";
    cout << charBuffer << endl;
    
    return 0;
}

The get() function gets the next character from the input stream. The get() function is overloaded, meaning it can accept a varying number of parameters depending on how it is used.

#include <iostream>

#define BUFFER 512

using namespace std;

int main(void){

char charBuffer[BUFFER];
char temp;


cout << "Enter a line of text" << endl;
cin.get(charBuffer, BUFFER, '\n');
cout << charBuffer << endl << endl;

//remove trailing newline
cin.get(temp);

cout << "Enter another line of text" << endl;
cin.get(charBuffer, '\n');
cout << charBuffer << endl << endl;


return 0;
}