如何向用户发出多个提示,具体取决于他们希望被C++提示的次数
How to issue multiple prompts to a user, depending on how many times they wish to be prompted C++
我正在C++中创建一个程序,该程序允许用户输入他或她希望被提示进行三个单独输入的次数,即
how many would you like: 2
enter here: 123.45/N 32.45/W Los Angeles
enter here: 22.22/N 223.4/E Hong Kong
我获得三个独立输入的方法是创建三个字符串变量,并执行以下操作:
cin << input1 << input2;
getline(cin, input3);
我在一个单独的文件中创建了一个解析器,它从前两个字符串中获取数字输入,并对其进行一些计算
我遇到的问题是可视化如何仅使用std库来设置系统,在std库中,我可以让用户输入他们想要输入位置的次数,然后让程序创建3个唯一的字符串,我可以在以后的计算中引用,并让它对用户输入的次数进行cin/getline处理。
我想到的一种方法是创建一个函数,该函数接受一个整数(用户输入的金额),并通过一个调用cin和getline的for循环。问题是,我如何保存和引用用户输入的值,以便以后进行计算?即
void inputAmount(int n) {
for(int i = 0; i < n; i++) {
cin << input1 << input2;
getline(cin, input3);
}
}
其中n是用户想要输入的行数。我试图创建一个字符串数组,并用(n*3)个元素初始化它,但这显然不适用于C++,因为变量必须是常量并声明。我只是困惑于如何进行,或者如何实现这一点。
您可以使用std::vector
而不是数组。std::vector
在编译时不需要大小。你的代码看起来像这样:
string input1, input2, input3;
int n; // number of lines
vector<string> v; // vector to hold the lines
// prompt user for number of lines
cout << "how many lines?" << endl;
cin >> n;
for (int i = 0; i < n; i++) {
cin << input1 << input2;
getline(cin, input3);
// parse and put back into input1, input2, etc. or some other variable as needed
v.push_back(input1);
v.push_back(input2);
v.push_back(input3);
}
对push_back()
的调用将元素添加到vector
中。您可以使用迭代器或[]
运算符(与数组相同)访问元素。最好创建一个struct
来将三个输入存储在一起,在这种情况下,您可以用struct
而不是string
来参数化vector
,但这是基本思想。
相关文章:
- 如何指定我希望我的LIB链接到的DLL文件?-Visual Studio 2019
- 有没有办法提示用户使用哪种数据类型作为模板 c++
- 我希望定义两个具有相同代码的不同名称的库
- 我希望改进或要求我目前的延迟/睡眠方法。C++
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 视觉我希望一个函数在另一个函数C++中进行计算
- 提示存档文件中的动态库依赖项
- 如何确保用户在一行上提示输入一次时输入名字和姓氏?
- 在 Golang 中等C++结构中提供代码提示/标记
- 如果第一个元素包含任何零,则我的程序以不希望的方式运行
- 是否可以/希望创建不可复制的共享指针模拟(以启用weak_ptr跟踪/借用类型语义)?
- 为什么 std::cin 不提示用户输入?
- 如何使用打印到 PDF 打印机在 MFC 和 CView 中以编程方式打印而不提示输入文件名?
- 如何在动态创建的CMFCToolbar的工具提示中添加描述?
- 如何在 c++ 中将密码和用户名保存到 .txt 文件中.如果用户尝试登录,我仍然希望能够检索它们
- 寻找解决这个动态编程问题的提示
- 这个编译器错误究竟希望我执行什么?
- 为什么这个涉及 std::enable_if 的模板元函数会产生不希望的结果?
- 如何向用户发出多个提示,具体取决于他们希望被C++提示的次数
- 如果用户使用了我希望他们使用的值表之外的值,我如何提示他们重新输入?