C++ language must use strings and c-strings similar to examples shown above task
C++
must use strings and c-strings similar to examples shown above task
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
int main() {
// getline example for C-Strings
char cStr[50];
cout << "Enter a line of input:";
cin.getline(cStr, 50);
cout << "cStr ==" << cStr << endl;
// getline example for the String data type
string str;
cout << "Enter a line of input: ";
getline(cin, str);
cout << "str = " << str << endl;
getline(cin, str, '?'); // Another version of getline
cout << "str = " << str << endl;
// cin.get example for char input
char ch;
cout << "Enter a character: ";
cin.get(ch);
cout << "ch == " << ch << endl;
// getline returns a reference
string s1, s2;
cout << "Enter a line of input:";
getline(cin, s1);
cout << s1 << endl;
cout << "s2 == " << s2 << endl;
// Mixing cin and getline
int n;
string line;
cout << "Enter an integer and a string: ";
cin >> n;
cin.ignore(50, '\n');
getline(cin, line);
cout << "line = " << line << endl;
// A string can behave like an array
string str_arr;
cout << "Enter a line of input:";
getline(cin, str_arr);
for (int i = 0; i < str_arr.length(); i++) {
cout << str_arr[i] << endl;
}
cout << endl;
for (int i = 0; i < str_arr.length(); i++) {
cout << str_arr.at(i) << endl;
}
return 0;
}
Task 1: Character Search
Write a program that reads a sentence from the user and then proceeds to ask the user to enter a character. Your program should then search for words in the sentence that start with the entered character and display them along with the number of words starting with that character.
Sample Interaction:
Enter a sentence: Hello World, this is Tom Clancy!
Enter a character: t
Words starting with 't' in the sentence are: this Tom
Number of words starting with 't': 2