【发布时间】:2016-10-25 21:43:15
【问题描述】:
我正在尝试制作 char 数组的动态数组
const int nameLength = 10;
int dataCount = 5;
// Initialize array of char array
char ** name;
name = new char*[dataCount];
for (int i = 0; i < dataCount; i++)
name[i] = new char[nameLength];
// Prompt for names
for (int i = 0; i < dataCount; i++) {
char userInput[nameLength];
cout << "Input data " << i << " :";
cin >> userInput;
name[i] = userInput;
}
cout << endl;
// Display data entered
for (int i = 0; i < dataCount; i++) {
cout << "Name" << i << " : " << name[i] << endl;
}
但是输出错误:
Input data 0 :abcde
Input data 1 :fghij
Input data 2 :klmno
Input data 3 :pqrst
Input data 4 :uvwxy
Name0 : uvwxy
Name1 : uvwxy
Name2 : uvwxy
Name3 : uvwxy
Name4 : uvwxy
如果我将输入部分更改为此,它将按预期工作:
cin >> name[i];
但在我的情况下,我不能直接将数据输入到变量中。
谁能解释代码有什么问题?我到处搜索,但似乎没有帮助
【问题讨论】:
-
然后使用
strcpy。或者更好std::vector<std::string>。为什么不能用最后的代码sn-p? -
优先使用
std::string,而不是 C 风格的字符数组。更喜欢使用std::vector而不是动态分配的数组。 -
实际上char数组在一个类中,我需要一个函数来输入char数组