我正在尝试制作一个包含多个用户输入字符串的数组,我已经厌倦了结构和动态数组,但它不起作用
我尝试制作一个包含字符串的结构,并尝试制作结构数组但没有成功
#include <iostream>
#include <string>
#include <limits>
using namespace std;
int main()
{
int rows;
cin >> rows;
string **arr = new string*[rows];
for( int i = 0; i < rows; ++i)
{
arr[i]= new string[1];
}
for(int i = 0; i < rows; ++i)
{
getline(cin, arr[i][0]);
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
for(int i = 0; i < rows; ++i)
{
cout << arr[i][0] << '\n';
}
for( int i = 0; i < rows; ++i)
{
delete [] arr[i];
}
delete [] arr;
return 0;
}
它允许 rows + 1 输入然后崩溃
最佳答案
使用 std::vector 和 std:string 类型轻松完成工作:
#include <iostream>
#include <string>
#include <limits>
#include <vector>
using namespace std;
int main()
{
int rows;
cin >> rows;
std::vector<std::string> vec;
std::string s;
// flush cin
std::getline(std::cin, s);
for (int i = 0; i < rows; ++i)
{
std::getline(std::cin, s);
vec.push_back(s);
}
for (int i = 0; i < rows; ++i)
{
cout << vec[i] << '\n';
}
return 0;
}
关于c++ - 将字符串输入多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57265938/