循环打印时出现分段故障
Segmentation fault when loop printing
我正试图创建一个简单的投票系统,通过循环使用makeGraph函数为每个投票打印一个星号,可以非常简单地获取结果并绘制图表。当它运行时,它接受输入并一直工作到makeGraph函数运行为止。它打印出数千个完全未格式化的星号,然后以"分段错误"结束
#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";
}
函数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;
}
相关文章:
- 分段故障(堆芯转储)矢量
- 数组的指针从不分段故障
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串
- 面临分段故障 使用 ffmpeg 读取视频时,因为"pFormatCtx-> streams [i]-> codecpar"的地址0x00
- 在C++中,当指向删除和指向不同对象时,分段故障指针
- 分段故障说明
- 分段故障(核心转储)-不知道为什么
- 分段故障线程
- hiredis SET遇到分段故障
- 分段故障,合并排序算法
- 多线程程序中的分段故障和gdb回溯上的不完整信息
- 到达主C++之前分段故障
- 分段故障核心使用 IF流转储
- 使用向量的移动键盘排列(分段故障)
- 在二进制树插入和遍历期间,我得到了分段故障
- 分段故障在类之间返回整数
- C++分段故障BST