Complete the code to read a string from the user using std::cin.
#include <iostream> #include <string> int main() { std::string name; std::cout << "Enter your name: "; std::cin [1] name; std::cout << "Hello, " << name << "!\n"; return 0; }
The operator >> is used with std::cin to read input into a variable.
Complete the code to read a full line of text (including spaces) into a string variable.
#include <iostream> #include <string> int main() { std::string sentence; std::cout << "Enter a sentence: "; std::getline(std::cin, [1]); std::cout << "You wrote: " << sentence << "\n"; return 0; }
The std::getline function reads a whole line into the string variable passed as the second argument.
Fix the error in the code to correctly output the string variable message.
#include <iostream> #include <string> int main() { std::string message = "Welcome!"; std::cout [1] message [2] std::endl; return 0; }
To output text with std::cout, use the insertion operator <<.
Fill both blanks to create a dictionary (map) comprehension that stores word lengths for words longer than 3 characters.
#include <iostream> #include <string> #include <map> #include <vector> int main() { std::vector<std::string> words = {"apple", "cat", "banana", "dog"}; std::map<std::string, int> lengths; for (const auto& word : words) { if (word.[1]() > 3) { lengths[word] = word.[2](); } } for (const auto& [w, len] : lengths) { std::cout << w << ": " << len << "\n"; } return 0; }
count() is incorrect because it does not exist for strings.size_t is a type, not a method.Use word.length() or word.size() to get the length of a string in C++. Both work, but here the first blank uses length() and the second uses size().
Fill all three blanks to create a map of uppercase words to their lengths for words longer than 4 characters.
#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> int main() { std::vector<std::string> words = {"apple", "cat", "banana", "dog", "elephant"}; std::map<std::string, int> result; for (auto word : words) { if (word.[1]() > 4) { std::transform(word.begin(), word.end(), word.begin(), ::[2]); result[[3]] = word.size(); } } for (const auto& [w, len] : result) { std::cout << w << ": " << len << "\n"; } return 0; }
size() instead of length() in the condition is acceptable but here only length() is correct.tolower instead of toupper changes to lowercase.The code checks if the word length is greater than 4 using length(). It converts the word to uppercase using toupper in std::transform. Finally, it uses the uppercase word as the key in the map.