循环打印时出现分段错误

时间:2014-10-03 12:58:17

标签: c++ segmentation-fault

我正在尝试创建一个简单的投票系统,通过循环makeGraph函数为每个投票打印星号,可以非常简单地获取结果和图形。当它运行时,它需要输入并运行直到makeGraph函数运行。它打印出数千个完全未格式化的星号,然后以#34;分段错误终止。"

#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";
}

1 个答案:

答案 0 :(得分:1)

您的函数makeGraph表示将返回string

string makeGraph(int val)

但是没有return值。您所要做的就是写信cout

这意味着这不起作用

cout << "Option 1: " << makeGraph(vote1) << "\n";

因为该函数没有将任何字符串值传递到输出流中。

我建议更改makeGraph功能,如下所示。

string makeGraph (int val)
{
    string graph = "";
    for (int i = 0; i < val; ++i)
    {
        graph += "*";   // Concatenate to a single string
    }
    return graph;
}