C++ While 循环跳过用户输入并重复直到完成

问题描述 投票:0回答:1

我正在做一个简短的挑战练习来练习 C++,我遇到了在 while 循环中请求用户输入的问题。

int i = 0;

do {
    int count = i + 1;  // Counter for the amount of celebrities entering.

    std::cout << "Celebrity Counter: " << count << "\n";
    std::cout << "Enter first name: ";
    std::cin >> first_name;
    
    std::cout << "\n";
    std::cout << "Enter last name: ";
    std::cin >> last_name;

    firstNames.push_back(first_name);  // Inserts input to vector firstNames.
    lastNames.push_back(last_name);  // Inserts input to vector lastNames.
    std::cout << "\n\n";
    i++;
  } while (i < 10);

每次运行都需要两个输入,然后将其添加到各自的向量中。但是,每当我运行它时,它都会完全跳过询问用户并仅打印以下内容:

Celebrity Counter: 1
Enter first name: 
Enter last name: 

Celebrity Counter: 2
Enter first name: 
Enter last name: 

Celebrity Counter: 3
Enter first name: 
Enter last name: 

Celebrity Counter: 4
Enter first name: 
Enter last name: 

依此类推,直到达到 i = 10。

我已经从人们遇到的类似问题中查找了解决方案,但它们要么不起作用,要么不适用于我的。该循环最初只是一个 while 循环,我将其更改为 do while 循环,看看这是否有所不同。我完全迷失了,因为感觉很简单,但我看不到它。

c++ while-loop user-input do-while
1个回答
0
投票

我认为下面的代码满足您的要求。另请注意,我使用

using namespace std;
来避免总是写
std::

#include <bits/stdc++.h>
using namespace std;
int main() {
  int count = 0;
  vector<string> firstNames, lastNames;
  string first_name, last_name;
  while (count < 10) {
    // Counter for the amount of celebrities entering.
    count++;
    cout << "Celebrity Counter: " << count << "\n";
    cout << "Enter first name: ";
    cin >> first_name;
    cout << "Enter last name: ";
    cin >> last_name;
    cout << "\n\n";

    firstNames.push_back(first_name); // Inserts input to vector firstNames.
    lastNames.push_back(last_name);   // Inserts input to vector lastNames.
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.