如果语句c ++

时间:2017-03-26 22:14:01

标签: c++ if-statement segmentation-fault boolean

我有一个返回bool变量的函数。然后我使用2 if语句来打印一些东西,具体取决于bool变量是true还是false。系统打印出分段错误,这很奇怪,因为我在beggining处将变量声明为false,因此程序总是打印false语句会更有意义。我唯一能想到的是,也许我写错了if语句?是否有某种方法为布尔变量写一个if语句?

这是输入

请输入输入文件的名称:40.txt 请输入首选金额1000

这是输出

有1600张支票可以查找所需金额的产品 分段错误(核心转储)

以下是if语句,但我将在下面添加整个代码

if(!found)
{
    cout << " the program did not find any matches. try again. ";
}
if(found)
{
cout << "the two numbers that add to your sum are " << n1 << " and " << n2 << ". These were found in position " << pos1 << " and " << pos2;
}

这里是整个代码

#include <iostream>
#include <fstream>
using namespace std;

int x, i, n1, n2, pos1 = 0, pos2 = 0, accesses = 0;

int readSortedArray(int array[20], int count, istream& infile)
{
    count = 0;
    while (infile >> array[count])
    {
        count++;

    }

    return count;
}

bool findproducts(int array[20],
                  int& n1,
                  int& n2,
                  int count,
                  int& accesses,
                  bool found,
                  int& pos1,
                  int& pos2)
{
    int sum;
    cout << "Please enter the prefered sum ";
    cin >> sum;
    for (i = 0; i < count; i++)
    {
        pos1++;
        n1 = array[i];
        pos2 = 0;
        for (x = 0; x < count; x++)

        {
            pos2++;
            accesses++;
            n2 = array[x];
            if (sum == n1 + n2)
            {
                found = true;
                i = count;
                x = count;
                return true;
            }

        }
    }
}

int main()
{
    int array[20];
    int answer, count = 0;
    bool found = false;

    std::string input_filename;
    ifstream infile;

    cout << "Please enter name of the input file: ";
    cin >> input_filename;
    infile.open(input_filename.c_str());
    if (!infile)
    {
        cout << "Could not open input file one\n";
        return 0;
    }

    count = readSortedArray(array, count, infile);

    found = findproducts(array, n1, n2, count, accesses, found, pos1, pos2);

    cout << "There were " << accesses << " checks made to find the products of your desired sum and" << endl;

    if (!found)
    {
        cout << " the program did not find any matches. try again. ";
    }
    if (found)
    {
        cout << "the two numbers that add to your sum are " << n1 << " and " << n2 << ". These were found in position " << pos1 << " and " << pos2;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您正在尝试将40个数字读入数组[20]。将所有20个更改为40(或使其保持不变),分段错误应该消失。可能最好在while (infile >> array[count])添加一个条款,检查计数小于数组的长度然后&amp;&amp;在括号中做你所拥有的。评论中的想法仍然是合法的,只要使程序正确运行并且可以理解,但是在数组末尾进行分配可能是您的分段错误的原因。