这段代码有什么问题?我想使用 string* 创建一个动态字符串数组,而不是集合、向量等。
int abc = 4;
string* abcdef = new string[abc];
for (int i = 0; i < abc; i++)
{
cin >> abcdef[i];
}
它没有给出任何错误,但我输入的数据没有出现在 VS2012 的本地框中。
问候
这工作得很好:
#include <iostream>
#include <string>
int main()
{
int count = 4;
std::string* stringArray = new std::string[count];
for (int i = 0; i < count; i++)
{
std::cin >> stringArray[i];
}
for (int i = 0; i < count; i++)
{
std::cout << "stringArray[" << i << "] = " << stringArray[i] << std::endl;
}
delete [] stringArray;
return 0;
}
不过,更好的解决方案仍然是:
int main()
{
std::vector<std::string> stringVector;
std::cout << "Enter Strings (Ctrl-Z to finish):" << std::endl;
std::copy(std::istream_iterator<std::string>(std::cin), std::istream_iterator<std::string>(), std::back_inserter<std::vector<std::string>>(stringVector));
std::copy(stringVector.begin(), stringVector.end(), std::ostream_iterator<std::string>(std::cout, "\n"));
return 0;
}
哦,看起来你的问题是关于 VS 调试器的。
这就是 VS 调试器显示指针内容的方式。它不知道它是一个数组,所以它只显示它指向的内容——第一个元素。要在监视窗口中显示所有这些,请键入“abcdef, 4”(其中 4 显然是数组的大小)。