Reputation: 912
I am trying to create a simple voting system that takes the results and graphs them very simply by looping through the makeGraph function printing an asterisk for each vote. When it runs, it takes input and works up until the makeGraph function is run. It prints out thousands of asterisks completely unformatted, then terminates with a "segmentation fault."
#include <iostream>
#include <string>
using namespace std;
string makeGraph(int val)
{
int i;
for (i = 0; i < val; i++)
{
cout << "*";
}
}
int main()
{
string title;
cout << "Enter a title: \n";
cin >> title;
int vote;
int vote1, vote2, vote3 = 0;
do
{
cout << "Enter vote option: 1, 2, or 3.\n";
cin >> vote;
if (vote == 1)
{
vote1++;
}
else if (vote == 2)
{
vote2++;
}
else if (vote == 3)
{
vote3++;
}
} while(vote != 0);
cout << title << "\n";
cout << "Option 1: " << makeGraph(vote1) << "\n";
cout << "Option 2: " << makeGraph(vote2) << "\n";
cout << "Option 3: " << makeGraph(vote3) << "\n";
}
Upvotes: 0
Views: 61
Reputation: 117876
Your function makeGraph
says it is going to return a string
string makeGraph(int val)
Yet there is no return
value. All you do is write to cout
.
That means that this will not work
cout << "Option 1: " << makeGraph(vote1) << "\n";
Because the function is not passing any string value into the out stream.
I would recommend changing the makeGraph
function as follows.
string makeGraph (int val)
{
string graph = "";
for (int i = 0; i < val; ++i)
{
graph += "*"; // Concatenate to a single string
}
return graph;
}
Upvotes: 1