Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;:如何使用char/string2d数组从用户处接受多个sentense?_C++ - Fatal编程技术网

C++ c++;:如何使用char/string2d数组从用户处接受多个sentense?

C++ c++;:如何使用char/string2d数组从用户处接受多个sentense?,c++,C++,以下代码失败: #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 &

以下代码失败:

#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;
}
#包括
#包括
使用名称空间std;
int main(){
INTA,b;
cout>a;
b=a-1;
字符串str[b];

对于(int i=0;i数组在编译时必须具有恒定的大小,因此要创建具有动态大小的数组,可以使用关键字
new
delete[]在堆上创建它以释放内存

还有,这其中的要点是什么:

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;
}

您需要清除输入缓冲区,将“您要提供多少输入?”中的换行符输入到第一个“输入字符串:”中

在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';
}
#包括
#包括
#包括
使用名称;
int main()
{
矢量输入;
串tmp;
while(getline(cin、tmp))
输入。推回(tmp);
用于(自动s:输入)
库特
#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';
}