我不知道为什么这不起作用,这是我第一次使用switch
声明。
int main() {
string typed;
ofstream theFile("players.txt");
ifstream theFile2("players.txt");
cout << "Do you want to read or write" << endl;
cin >>typed;
switch(typed){
case "write":
cout << "Enter players Id, Name and Money" << endl;
cout << "Press Ctrl+Z to exit\n" << endl;
while(cin >> idNumber >> name >> money){
theFile << idNumber << ' ' << name << ' ' << money << endl;
}break;
case "read":
while (theFile2 >> id >> nametwo >> moneytwo){
cout << id << ", " << nametwo << ", " << moneytwo << endl;
}break;
}
}
答案 0 :(得分:1)
正常的平等测试没有错:
if( typed == "write" ) {
// ...
} else if( typed == "read" ) {
// ...
} else {
cout << "Whoops, try again" << endl;
}
switch
的优点在这种情况下无关紧要,您无法打开字符串值。它只能用于原始数据类型。
还有其他解决方案使用switch
,但这些解决方案涉及将字符串值映射到整数常量,这对您的应用程序来说太过分了。所以,虽然我会提到它是可能的,但我不会提供任何细节来避免使代码膨胀的诱惑。
答案 1 :(得分:0)
我认为这些人根本没有想象力!如果没有字符串开关,那就让我们创建一个!下面是一个不如我想要的那样好的例子。
#include <iostream>
#include <fstream>
#include <string>
#include <utility>
void sswitch (std::string const&)
{
}
template <typename F, typename... T>
void sswitch (std::string const& value, F&& arg, T&&... args)
{
if (value == arg.first) {
arg.second();
}
else {
sswitch(value, std::forward<T>(args)...);
}
}
template <typename F>
std::pair<std::string, F> scase(std::string const& s, F&& f)
{
return std::make_pair(s, std::forward<F>(f));
}
int main()
{
std::ofstream theFile("players.txt");
std::ifstream theFile2("players.txt");
std::string input;
if (std::cin >> input) {
sswitch(input,
scase("write", [&]{
std::cout << "Enter players Id, Name and Money\n";
std::cout << "Press Ctrl+Z to exit\n\n";
int idNumber, name, money;
while(std::cin >> idNumber >> name >> money) {
theFile << idNumber << ' ' << name << ' ' << money << '\n';
}
}),
scase("read", [&]{
int id, nametwo, moneytwo;
while (theFile2 >> id >> nametwo >> moneytwo){
std::cout << id << ", " << nametwo << ", " << moneytwo << '\n';
}
})
);
}
}