gpt4 book ai didi

c++ - 如何将用户定义的字符串转换为整数

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:03:13 25 4
gpt4 key购买 nike

我基本上要求用户输入一个字符串,假设他们输入“ABC”或“DEF”

然后,如果输入 ABC,我想设置某个整数 = 1,如果输入 DEF,则设置为 2。

如果输入任何其他内容,那么我希望它说出无效值。

所以最后,如果输入了有效值,我会将整数分配给 1 或 2。

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
string input = "";

// How to get a string/sentence with spaces
cout << "Please enter a valid sentence (with spaces):\n>";
getline(cin, input);
cout << ".\n" << "You entered: " << input << endl << endl;

int m
if(input = ABC)

return 0;
}

最佳答案

非常简单:

#include <iostream>
#include <map>
#include <string>

int main()
{
std::map<std::string, int> const v { { "ABC", 1 }, { "DEF", 2 } };

for (std::string line; std::getline(std::cin, line); )
{
auto it = v.find(line);

if (it == v.end())
{
std::cout << "Input '" << line << "' is invalid.\n";
}
else
{
std::cout << "Your input value: " << it->second << "\n";
}
}
}

关于c++ - 如何将用户定义的字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27325634/

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