Cpp - Write program to read and output text with string class


Create a program that defines a string containing the following character sequence:

this is a test!  

Displays the length of the string on screen.

Read two lines of text from the keyboard.

Concatenate the strings using " - " to separate the two parts of the string.

Output the new string on screen.


#include <iostream>    // Declaration of cin, cout 
#include <string>      // Declaration of class string 
using namespace std; 

int main() //from ww w .j av  a2s . c om
    string message("this is a test!\n"), 
            prompt("Please input two lines of text:"), 
            str1, str2, sum; 

    cout << message << endl;   // Outputs the message 

    cout << prompt << endl;    // Request for input 

    getline( cin, str1);      // Reads the first 
    getline( cin, str2);      // and the second line of text 

    sum = str1 + " - " + str2;   // Concatenates, assigns 
    cout << sum << endl;         // and outputs strings. 

    return 0; 


Related Exercise