I am trying to do a for loop which will allow the user to type in the name of a subject for a number of times the user has already indicated. However, whenever I use this program, I only input the name for the first subject before getting a Segmentation Fault. How can I fix it? Here is the main portion of the code that is giving me trouble.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int main( )
{
string a;
int b;
string c[b];
cout << "Enter your name.\n";
cin >> a;
cout << "Enter the number of classes you are taking.\n";
cin >> b;
for (int i = 0; i < b; i++)
{
cout << "Enter the name of Class " << i + 1 << endl;
cin >> c[i];
}
The size of an automatic array must be specified with a compile-time constant, so that code isn't legal. You may want to disable the compiler extension that allows it.
If you need an array and don't know the size at compile time, use a std::vector.
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::cout << "Enter your name.\n" ;
std::string name ;
std::cin >> name ;
std::cout << "Enter the number of classes you are taking.\n" ;
unsigned numClasses ;
std::cin >> numClasses ;
std::vector<std::string> classes(numClasses) ;
for ( unsigned i=0; i<numClasses; ++i)
{
std::cout << "Enter the name of class " << i+1 << '\n' ;
std::cin >> classes[i] ;
}
}
Line 17 creates a vector with numClasses elements which are copy constructed from the second parameter in the constructor (which is a default-constructed element by default.)