有条件地打破一长串输入? [英] Conditionally Breaking A Long Sequence Of Inputs?

查看:58
本文介绍了有条件地打破一长串输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从事一个个人项目。要工作,它需要(相对地)从用户那里接收大量数据,以12个用户的四种不同类型的数据的形式。因此,我有很长的语句序列类似于此:

I have a personal project I've been working on. To work, it needs to accept a lot of data (relatively) from the user, in the form of four different kinds of data for 12 users. As such, I have quite a lengthy sequence of statements similar to this:

cout << '\n' << "Monster A's name is: ";
cin >> nameA;
cout << '\n' << "Monster A rolled: ";
cin >> rollM_A;
cout << '\n' << "Monster A's Dex is: ";
cin >> DexA;
cout << '\n' << "Monster A's Mod is: ";
cin >> ModA;
cout << '\n' << "Monster A's Level is: ";
cin >> LvlA;

等。

有时,可能只需要输入少于12个怪物的数据,例如5-6,甚至1-2。我希望能够使用命令基于击键之类的内容将输入部分跳过到代码的其余部分。例如,如果用户输入了5个怪物的数据,这就是他们所需要的,他们可以按反斜杠跳过其余的输入序列。

Occasionally, however, there might only be a need to input data for less than 12 monsters, say, 5-6 or even 1-2. I'd like to be able to use a command to skip the input section to the rest of the code based on something like a keystroke. i.e. If the user has put in data for 5 monsters, and that's all they require, they could hit the backslash to skip the rest of the input sequence.

在谈论任何意义/是否有STL命令可以执行我要寻找的操作?目前,此过程尚未循环,但是如果处于循环中,退出过程会更容易吗?我确实想过尝试这样的事情:

Does what I'm talking about make any sense/is there an STL command to do what I'm looking for? Currently, this process isn't looped, but would exiting it be easier if it was inside a loop? I did have a thought of trying something like this:

while(cin.get() != '\') {
   cout << '\n' << "Monster A's name is: ";
   cin >> nameA;
   //etc...
}

编辑:上面的尝试已建立,但是在输入所需的击键后,它会快速无休止地打印用户提示,而不接受数据。有什么建议吗?我想要的只是让它破裂并继续前进。我可以有效地使用switch语句吗?

The above attempt builds, but upon entering the desired keystroke, it quickly and endlessly prints the user prompts without accepting data. Any advice? All I want is for it to break and move on. Can I use a switch statement effectively?

谢谢!

推荐答案

我只是测试了这组代码,它似乎可以按照您的意愿工作。当然,您将不得不对其进行修改以适合您的原始应用程序。

I just tested this set of code and it seems to work how you would like. Of course you will have to modify it to fit your original application.

std::string in;

while (true) {
    std::cout << "Enter a name\n";
    std::cin >> in;
    if (in == "#")
        break;
    std::cout << "\nMonster A's name is: " << in << "\n";
}

为了纳入怪物数量的限制,而不是 true 参数传递到while循环中,只需添加一个计数器即可创建多少个怪物并在此条件下中断:

In order to incorporate the limit of the number of monsters, rather than having the true parameter passed into the while loop, simply add a counter to how many monsters are created and break on that condition:

int num_monsters = 0;
while (num_monsters <= 12) {
    ...
    num_monsters++;
}

希望这会有所帮助。

这篇关于有条件地打破一长串输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆