FOR C++ Modify Program One to add the following:1) Assignment operator (“=”). 2)
ID: 3850381 • Letter: F
Question
FOR C++
Modify Program One to add the following:1) Assignment operator (“=”).
2) Comparison operators (“<”, “<=”, “==”, “!=”, “>=”, “>”)3) Concatenation operator (“&”).4) Concatenation and assignment operator (“&=”)5) Input operator (“>>”).6) Output operator (“<<”).
Above items 1 through 4 should have versions that work with a String object and a “C” type
string on the right of the operator.Items 5 and 6 require a String object to the right of the operator.Items 1 and 4 will require a String object on the left of the operator.Items 2 and 3 should have versions that allow both a String object and a “C” type string on
the left of the operator.Item 3 does not modify the object to the left of the operator.
Explanation / Answer
The code is given below :
#include <iostream>
#include <iomanip>
#include <string> // needed to use the string class
using namespace std;
int main() {
string msg1("hello");
string msg2("HELLO");
string msg3("hello");
// Relational Operators (comparing the contents)
cout << boolalpha;
cout << (msg1 == msg2) << endl; // false
cout << (msg1 == msg3) << endl; // true
cout << (msg1 < msg2) << endl; // false (uppercases before lowercases)
// Assignment
string msg4 = msg1;
cout << msg4 << endl; // hello
// Concatenation
cout << (msg1 + " " + msg2) << endl; // hello HELLO
msg3 += msg2;
cout << msg3 << endl; // helloHELLO
// Indexing
cout << msg1[1] << endl; // 'e'
cout << msg1[99] << endl; // garbage (no index-bound check)
// cout << msg1.at(99) << endl; // out_of_range exception
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.