如何在 c++ 中制作字符串数组

How to make string array in c++?

本文关键字:字符串 数组 c++      更新时间:2023-10-16

我是C++新手。我想制作一个字符串数组,其中我想保存板球队球员的名字。我想以数组的形式保存它,如下所示:

player[1]= sachin;
player[2]= john smith;

我使用了下面的程序,但出现以下错误:

错误 1错误 C2661:"std::basic_istream>::getline":没有重载函数占用 1 个参数
#include "stdafx.h"
#include <iostream>
#include<string>
int main()
{
    using namespace std;
    string player[3];
    int i;
    for (int i = 1; i <= 3; i++)
    {
        std::getline(cin, player);
    }
}

如何像保存数字数组一样保存字符串数组。

  1. for (int i = 1; i <= 3; i++)替换为for (int i = 0; i <= 2;i++)
  2. getline()经常会导致错误,如果您使用的是某种版本的 Linux,它就不会简单地工作。
  3. 您没有正确索引数组,因为它应该player[i],而不仅仅是player
  4. 如果您使用的是using namespace std;那么更好的声明方法是在 main 函数外部声明它。

以下代码应该执行您尝试执行的操作。

#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
    string player[3];
    int i;
    for (int i = 0; i < 3; i++) {
        cin >> player [i];
    }
}