简体   繁体   English

如何解决这段代码中的分段错误?

[英]How to resolve the segmentation fault in this code?

I am trying to make an infix calculator for which I am currently trying to convert numbers entered in a character array to double.我正在尝试制作一个中缀计算器,我目前正在尝试将字符数组中输入的数字转换为双精度计算器。

here's my code:这是我的代码:


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

int main()
{
    char exp[500];
    const int SIZE = 100;
    char temp[SIZE];
    char op;

    int strLen = 0, k, l, num = 0, fnum = 0;
    double number = 0;

    cin.getline(exp, 500,'\n');

    int i = 0, j = 0, fpoint=0;

    cout << exp;

    for (i = 0, j = 0; exp[j] != 0; i++)
    {
        if (i % 2 == 0)
        {
            for (int m = 0; exp[m] != ','; m++) //stopped working
                temp[m] = exp[m];
            
            cout << temp;
            
            for (k = 0; k < SIZE && temp[k] != 0; k++)
            {
                strLen = k;
                if (temp[k] == '.')
                    fpoint = k + 1;
            }

            cout << fpoint<<endl;


            cout << "strLen" << strLen;

            for (k = 0; k <= fpoint; k++)
            {
                num = num + ((temp[fpoint - k] - '0') * pow(10, k));
            }

            for (k = fpoint + 1, l = 0; k <= strLen; k++, l++)
            {
                fnum = fnum + ((temp[strLen - l] - '0') * pow(10, l));
            }

            number = num + (fnum / pow(10, strLen - fpoint + 1));

            cout << number;

            j = j + strLen + 1;

        }
        else
        {
            char op = temp[j];
            cout << op;
        }
    }
    system("pause");
    return 0;
}


sample input样本输入

2.5*3

It stops working and gives segmentation fault as an error on the marked position.它停止工作并将分段错误作为标记位置的错误。

这一行for (int m = 0; exp[m] != ','; m++) //stopped working will always fail if there are no , characters since exp[m] != ','将始终等于true因此将超出exp数组的末尾,从而触发“分段错误”。

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

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