如何向用户发出多个提示,具体取决于他们希望被C++提示的次数

How to issue multiple prompts to a user, depending on how many times they wish to be prompted C++

本文关键字:提示 希望 他们 取决于 C++ 用户      更新时间:2023-10-16

我正在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,但这是基本思想。

相关文章: