你想大概是宣布你的阵列这样什么:
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;
}
你为'system'包含''吗? –
0x499602D2
你能描述你遇到的问题吗? – 0x499602D2
你在问这个SO问题有什么问题?从哪里开始... –