cin 输入用户,用于动态分配字符串数组

cin input user for dynamic allocation of array of strings

我是新手,学习c++,尝试动态分配一个字符串数组并由用户输入每个字符串。所以首先,用户输入字符串的数量,然后使用 cin>>

放置每个字符串
int main() {


    int numberOfTeams;
    char** Teams;

    cout << "Enter the number of teams " << endl;
    cin >> numberOfTeams;

    Teams = new char* [numberOfTeams] ;

    
    for (int i = 0; i < numberOfTeams; i++) {
        
            cin >> Teams[i];
                
    }

    delete[] Teams;

    return 0;
}

程序在 cin 一个字符串后将我抛出。 我得到的错误是:

 Exception thrown: write access violation.
**_Str** was 0xCEDECEDF.

我不能使用可验证的“字符串”,只能使用字符数组。

谢谢大家

像这样

const int MAX_STRING_SIZE = 1024;

int main() {


  int numberOfTeams;
  char** Teams;

  std::cout << "Enter the number of teams " << std::endl;
  std::cin >> numberOfTeams;

  Teams = new char*[numberOfTeams];
  for (int i = 0; i < numberOfTeams; i++) {
    Teams[i] = new char[MAX_STRING_SIZE];
    std::cin >> Teams[i];
  }
  for(int i = 0; i < numberOfTeams; ++i) {
    delete [] Teams[i];
  }
  delete [] Teams;

  return 0;
}

char** 是指向字符指针数组的指针。你做的第一件事是分配字符指针数组 Teams = new char*[numberOfTeams]; Teams 现在指向 numberOfTeams char* 指针中的第一个 char*。您的错误是,对于数组中的每个 char* 指针,您没有执行分配。这是正确的解决方案。

#include <iostream>
using namespace std;
int main() {

    int numberOfTeams;
    int teamNameLength = 32;
    char **Teams;

    cout << "Enter the number of teams " << endl;
    cin >> numberOfTeams;
    Teams = new char*[numberOfTeams];

    for (int i = 0; i < numberOfTeams; i++)
    {
        Teams[i] = new char[teamNameLength];
    }

    for (int i = 0; i < numberOfTeams; i++) {
        cout << "Enter team name " << i+1 << endl;
        cin >> Teams[i];
    }

    for (int i = 0; i < numberOfTeams; i++) {
        delete[] Teams[i];
    }
    delete[] Teams;

    return 0;
}