C++:如何使用char/string 2d数组接受来自用户的超过1个参数?

问题描述:

下面的代码失败:C++:如何使用char/string 2d数组接受来自用户的超过1个参数?

#include <iostream> 
#include <string> 
using namespace std; 

int main(){ 
    int a, b; 
    cout << "how many input you want to give ? "; 
    cin >> a; 
    b = a - 1; 
    string str[b];    
    for(int i = 0; i <= b; i++){ 
     cout << "Enter a string: "; 
     getline(cin, str[i]); 
    } 

    for(int k = 0; k < a; k++){ 
     cout << "You entered: " << str[k] << endl; 
    } 

    return 0; 
} 

但如果我固定的值“诠释了”,然后运行代码。请帮忙。

数组在编译时必须具有固定的大小,因此要创建一个具有动态大小的数组,您可以使用关键字newdelete[]在堆上创建它以释放内存。

还什么是点:

cin >> a; 
b = a - 1; //? 

您可以轻松地做到这一点是这样的:

int n; 
cout << "how many input you want to give ? "; 
cin >> n; 
string* str = new string[n];    
for(int i = 0; i < n; i++){ 
    cout << "Enter a string: "; 
    getline(cin, str[i]); 
} 

for(int k = 0; k < n; k++){ 
    cout << "You entered: " << str[k] << endl; 
} 

不要忘记清洁时,即可大功告成:

delete[] str; 

你会想要清除输入缓冲区,换行符是“你想给多少输入?”被输入到第一个“输入字符串:”。

在cin >> a;后添加此行。

cin.ignore(INT_MAX, '\n'); 

使用一个向量来存储输入。

#include <vector> 
#include <string> 
#include <iostream> 
using names pace std; 

int main() 
{ 
    vector <string> input; 
    string tmp; 

    while (getline(cin, tmp)) 
     input.push_back(tmp)); 

    for(auto s : input) 
     cout << s << '\n'; 
}