Reputation: 95
I have a code here:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int a, b=0,d,f=1;
string c, e, g;
cout<<":"<<endl;
cin>>a;
string question[a];
for(;b<a;b++)
{
cout<<"#"<<b+1<<":"<<endl;
getline(cin,c);
question[b]=c;
cout<<":"<<endl;
cin>>d;
getline(cin,e);
question[b][d+1]{e};
for(;f<d;f++)
{
cout<<" #"<<f<<":"<<endl;
getline(cin,g);
question[b][f]=g;
}
}
system("pause");
return 0;
}
This does not compile and I believe it is because the variables -that I want to define the first availabe spaces in arrays as- are seen as characters and not their values that would be defined by the user input. I'm trying to get my bearings on C++ right now; could somebody explain to me in simple terms why this does not work and how I should fix my problem?
Error:
Error 1 expected constant expression 12
Error 2 cannot allocate an array of constant size 0 12
Error 3 'question' : unknown size 12
Error 4 syntax error : missing ';' before '{' 21
Error 5 syntax error : missing ';' before '}' 21
Error 6 '=' : cannot convert from 'std::string' to 'char' 27
Error 7 IntelliSense: expression must have a constant value 12
Error 8 IntelliSense: expected a ';' 21 19
Upvotes: 0
Views: 51
Reputation: 4012
This does not compile because you're trying to make an array's size dependant on the user input, and in c++
the array size needs to be already known at compile time. Change
string question[a];
to
string *question = new string[a];
and just before return 0
do:
delete [] question;
Also this line:
question[b][d+1]{e}
doesn't really have sense. The first index is gonna access element b
of the array, the second one will access element d+1
of the string, and you're trying to do something with a string there. Strings are built of characters, not other strings. Same appplies to line 27
.
Upvotes: 1
Reputation: 2137
The problem is likely your attempt to have an array of strings of size a
when a
is not
known at compile time.
cout<<"Enter the number of questions:"<<endl;
cin>>a;
string question[a]; //Creates an array for questions
You could use a std::vector
of strings instead of a c-style array. A std::vector
allows for the size to change dynamically.
You could also allocate an array on strings on the heap, by using
string* question_ptr = new string[a];
And then calling when done with the array:
delete[] question_ptr ;
Upvotes: 1
Reputation: 1761
C++ isn't big on variable-length arrays, so this
string question[a];
is going to be bad news. The usual C++ idiom for that sort of thing is a vector
or (in C++11) an array
.
Upvotes: 0