Conversation wit
Here is a complete C++ code sample that initializes an array of 5 names, takes input using std::cin >>, and searches for the name using std::find from the <algorithm> header:
C++
#include <iostream>
#include <string>
#include <algorithm> // Required for std::find
#include <iterator> // Required for std::begin and std::end
int main() {
// 1. Array of 5 names
std::string names[5] = {"Alice", "Bob", "Charlie", "Diana", "Ethan"};
// 2. Get input from user using std::cin
std::string targetName;
std::cout << "Enter a name to search for: ";
std::cin >> targetName;
// 3. Search using std::find from <algorithm>
// std::find returns an iterator pointing to the found element, or std::end if not found.
auto result = std::find(std::begin(names), std::end(names), targetName);
// 4. Output the result
if (result != std::end(names)) {
// Find the index by calculating distance from the beginning
int index = std::distance(std::begin(names), result);
std::cout << "Success! '" << targetName << "' was found at index " << index << ".\n";
} else {
std::cout << "Sorry, '" << targetName << "' was not found in the array.\n";
}
return 0;
}

Tidak ada komentar:
Posting Komentar