Segmentation Fault

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];
	}
Assigning a value to 'b' before using it
Last edited on
line 5, use "string c = new string [b]" instead, but as maeriden mentioned assign a value to 'b' before using it.
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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] ;
    }
}
Sorry to hijack this thread. I'm just interested in what Cire wrote.

By line 17:
std::vector<std::string> classes(numClasses) ;

Is this line creating a vector with 'numClasses' indices, then populating them with cin-input?

i.e.
Line 17 is essentially pushing_back with empty strings, then the user fills them.
Last edited on
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.)

See http://www.cplusplus.com/reference/vector/vector/vector/
(Constructor #2.)

I didn't want to stray too far from the array way of doing things, not knowing the OPs level of familiarity with the std::vector class.
Topic archived. No new replies allowed.