我现在很困惑
这里有什么问题,我该怎么做才能解决问题
编辑: omg我很抱歉...我现在只是如此波动,以至于我甚至无法提出问题
我想将10个输入字符串分配给指针数组。
using namespace std;
int main(int argc, char *argv[])
{
char *mess[10];
int i = 0;
for (; i < 10; i++)
{
cout << "Enter a string: ";
cin.getline(mess[i], 80);
}
for (i = 0; i < 10; i++)
cout << mess[i];
system("PAUSE");
return EXIT_SUCCESS;
}
答案 0 :(得分:3)
你想要的可能是这样声明你的数组:
char mess[10][80];
当您从getline阅读最多80个字符时。
您当前的实现构建了一个10 char*
的数组,它们从未被初始化为指向已分配的缓冲区。
更安全的方法是使用std::string
,因为将为您处理缓冲区大小。一个简单的改变:
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
std::string mess[10];
int i = 0;
for (; i < 10; i++)
{
cout << "Enter a string: ";
cin >> mess[i];
}
for (i = 0; i < 10; i++)
cout << mess[i] << endl; // you probably want to add endl here
system("PAUSE");
return EXIT_SUCCESS;
}
应该给你你想要的东西。
修改强>
如果你绝对需要char *
(这不是一个好主意),这就是你要找的东西:
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
char* mess[10];
int i = 0;
for (; i < 10; i++)
{
cout << "Enter a string: ";
mess[i] = new char[80]; // allocate the memory
cin.getline(mess[i], 80);
}
for (i = 0; i < 10; i++)
{
cout << mess[i] << endl;
delete[] mess[i]; // deallocate the memory
}
// After deleting the memory, you should NOT access the element as they won't be pointing to valid memory
system("PAUSE");
return EXIT_SUCCESS;
}
答案 1 :(得分:2)
你正在分配10个指针,但绝不会将它们初始化为指向getline可以读取输入的空间。
答案 2 :(得分:2)