简体   繁体   English

循环打印时出现分段错误

[英]Segmentation fault when loop printing

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. 我正在尝试创建一个简单的投票系统,该系统将获取结果并通过循环makeGraph函数为每个投票打印一个星号非常简单地对其进行图形处理。 When it runs, it takes input and works up until the makeGraph function is run. 当它运行时,它会接受输入并起作用,直到运行makeGraph函数。 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";
}

Your function makeGraph says it is going to return a string 您的函数makeGraph表示它将返回一个string

string makeGraph(int val)

Yet there is no return value. 但是没有return值。 All you do is write to cout . 您要做的就是写给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. 我建议如下更改makeGraph函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM