如何创建循环并使用 push_back()

How to create loops and use push_back()

我试图让用户选择他们想要添加的名称数量,然后使用 push_back() 将那么多名称添加到列表中。

我是编程新手,很迷茫。

这是我目前的代码:

int main()
{
    int numNames;
    std::cin >> numNames;
    vector<string> names;
    numNames = read_integer("How many names would you like to add?");

    for (int i = 0; i < numNames; i++)
    {
        names[i] = read_string("Enter name:");
        i++;

        while (cin >> numNames)
        {
            names.push_back(read_string("First value:"));
        }
    }

使用 std::vector 时,无需让用户预先输入姓名数。这就是让 std::vector 为您处理内存管理的好处。您只需读取并验证向量的输入和 .push_back(),直到用户完成。使用 getline() 作为输入允许您读取带有空格的名称(例如 "first last"),而使用 std::cin 将在遇到第一个空格时停止读取。

使用 getline() 还为用户提供了一种简单的方法来表明他们已完成输入姓名。让用户在新行上单独按 Enter 而不是名称将导致由 getline() 填充的字符串具有 .size() == 0。你只是在那个时候打破了你的read-loop。

读取名称并添加到 std::vector<std::string> 的简短示例可以类似于:

#include <iostream>
#include <string>
#include <vector>

int main()
{
    std::vector<std::string> names {};    /* vector of strings */
    std::string tmp {};                   /* temp string */
    
    std::cout << "Enter names below, [Enter] alone when done\n\n  name: ";
    
    /* read line while input size isn't 0 */
    while (getline (std::cin, tmp) && tmp.size() != 0) {
        names.push_back (tmp);            /* add input to vector */
        std::cout << "  name: ";          /* next prompt */
    }
    
    std::cout << "\nnames collected:\n\n";
    for (const auto& name : names) {      /* loop over each name and output */
        std::cout << name << '\n';
    }
}

例子Use/Output

$ ./bin/vector-string-names
Enter names below, [Enter] alone when done

  name: Mickey Mouse
  name: Minnie Mouse
  name: Pluto (the dog)
  name: Donald Duck
  name: Daffy Duck
  name: Daisy Duck
  name: Hughie Duck
  name: Louie Duck
  name: Dewy Duck
  name:

names collected:

Mickey Mouse
Minnie Mouse
Pluto (the dog)
Donald Duck
Daffy Duck
Daisy Duck
Hughie Duck
Louie Duck
Dewy Duck

补充说明

虽然 using namespace std; 为简短示例程序提供了便利,但请参阅 Why is “using namespace std;” considered bad practice?

从不 std::cin >> numNames; 不检查输入后的 stream-state。 (特别是当涉及到数字转换时)。一个简单的:

  if (!(std::cin >> numNames)) {
    std::cerr << "error: invalid integer input.\n";
    return 1;
  }

为确保用户提供有效的整数输入,您可以不断循环,直到输入有效的 int,然后在输入有效整数后 break 读取循环。您可以使用 .clear() 并使用 .ignore()stdin 中删除输入失败后和下一次输入之前的所有无效字符。

我注意到当你进行循环时,有一种更简单的方法可以防止一些额外的和不需要的错误:

    for (int i = 0; i < numNames; ++i)
    {
        names[i] = read_string("Enter name:");

        while (cin >> numNames)
        {
            names.push_back(read_string("First value:"));
        }
    }

这样,您就不会将 i 的值加倍。当开始 for-loop 时,使用 i++ 会向 i 加 1,但不会更新 i 并且只会向 returns i 添加 1。使用 ++i 更新和 returns i 加 1,您不再需要额外的行 i++,这将防止加倍 i.