Reputation: 595
It doesn't run the second for loop and also skips system("pause"). Can anyone explain what is wrong in my code? I want to make two arrays of strings: strgs1 and strgs2 of length a and b, and then take the input from the user for each element of the arrays. This is my code:
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main(){
int a,b;
cin>>a>>b;
string strgs1[a-1], strgs2[b-1];
for(int i = 0;i < a;i++){
cin>>strgs1[i];
}
for(int j = 0;j < b;j++){
cin>>strgs2[j];
}
system("pause");
return 0;
}
Upvotes: 0
Views: 1180
Reputation: 2287
Suppose you enter a=3. The size of the array is a-1=2. The loop iterates i=0, i=1, i=2. But this is 3 elements, while your vector has only size 2!
Furthermore, use std::vector. Arrays with non constant size are allowed by some compilers, but it is not portable.
Upvotes: 0
Reputation: 480
First point, you are using static arrays string strgs1[a-1], strgs2[b-1];
with sizes non-constant at compile time. That's a bad idea. I would advice to use std::vector instead.
Second point, the sizes that you are using for your arrays are not good. For example, the size of your first array is a-1
and you try to insert a
strings inside it (from 0 to a-1).
Upvotes: 2