如何让用户在 C++ 中选择一个数字

Posted

技术标签:

【中文标题】如何让用户在 C++ 中选择一个数字【英文标题】:How do i get a user to pick a number in c++ 【发布时间】:2019-11-28 16:36:23 【问题描述】:

我试图让用户选择一个数字,这会导致 C++ 中的另一个代码我该怎么做?

cout << "Choose a text: "
getline(????)

1:
code number one

2.
text number 2

【问题讨论】:

“导致另一个代码”是什么意思?你的意思是用户选择一个行号并执行该行的代码吗?你的意思是如果用户选择了某个值,就会执行一些代码,或者执行一些其他代码? 【参考方案1】:

选择一个数字? 我假设您正在谈论输入整数。 getline 主要用于字符串和每个单词或单词之间的空格。 例如,如果输入类似于“感恩节快乐” 代码如下:

#include <iostream>
#include <string> //to use getline(cin, variable_name)
using namespace std;

int main()

     string sentenceWithSpace;
     cout << "get input" << endl;
     getline(cin,sentenceWithSpace);
     cout << sentenceWithSpace << endl;
     system("pause"); // include this line if you use VS
     return 0;

如果用户只是输入像 1,2,3,4,5,6 这样的值

#include <iostream>
using namespace std;

int main()

     int thisIsJustAInteger;
     cout << "get input" << endl;
     cin >> thisIsJustAInteger;
     cout << thisIsJustAInteger << endl;
     system("pause"); // include this line if you use VS
     return 0;

【讨论】:

以上是关于如何让用户在 C++ 中选择一个数字的主要内容,如果未能解决你的问题,请参考以下文章