gpt4 book ai didi

C++ 用户可以使用 cin 创建新字符串吗?

转载 作者:太空狗 更新时间:2023-10-29 21:04:00 26 4
gpt4 key购买 nike

我做了一本字典。我的目标是让用户输入新词并定义它们。

我想我已经记下了“定义词”部分,并且我已经记下了其余部分。我在下面写了一个我正在寻找的例子。我不想有人为我做这件事;我只想知道是否有办法做到这一点,以及我可以在哪里学到更多。

现在,我正在使用 C++ for Dummies 和 Sam 的 Teach Yourself For Teachers。

string newword
string word

cout << "Please enter a word" >> endl;
cin >> word;
if (word == newword)
{
create string <newword>; // Which would make the following
// source code appear without
// actually typing anything new
// into the source code.
}
string newword
string word
string word2 // which would make this happen

cout << "Please enter a word" >> endl;
cin >> word;
if (word == newword)
{
create string <newword>
}

最佳答案

我会使用 std::map因为,嗯,它是一个字典式的容器。 map容器非常适合这种情况,您可以提供唯一键来匹配其他数据。由于典型的词典每个单词只有一个条目,所以这是完美的。

typedef 允许我们定义一个带有名称的类型。这在这里很有用,因为我们不必输入 std::map<std::string, std::string>一遍又一遍。想象一下每次你看到 Dictionary , 它被替换为 std::map<std::string, std::string>

// Map template requires 2 types, Key type and Value type.
// In our case, they are both strings.
typedef std::map<std::string, std::string> Dictionary;
Dictionary myDict;

然后我会要求用户输入,然后要求他们定义他们的条目。

std::string word;
std::cout << "What word would you like added to the dictionary?" << std::endl;
std::cin >> word;

std::string definition;
std::cout << "Please define the word " << word << std::endl;
std::cin >> definitiion;

下一步只需将单词及其定义插入字典即可。使用 [] map 上的运算符,我们替换提供的键 word 已经存在的任何条目.如果它不存在,它将作为新条目插入。请注意,任何以前定义的同名单词现在都有一个新定义!

myDict[word] = definition;

运行它会产生类似于:

>> What word would you like added to the dictionary?
>> Map
>> Please define the word Map
>> Helps you find things

访问 map 中的定义现在很简单:

myDict["Map"]; // Retrieves the string "Helps you find things"

关于C++ 用户可以使用 cin 创建新字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487749/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com