额外循环导致分段错误

时间:2014-06-12 16:13:52

标签: c++ string segmentation-fault

我有一个奇怪的问题。每当我添加一个额外的循环运行T次时,它会导致分段错误。我正在尝试解决这个问题:http://www.spoj.com/problems/ABSYS/ 因此,如果我逐个输入输入测试用例,它会产生正确的输出。但是,当我尝试接受T次输入时,会导致分段错误。 我试图调试它说“s无法访问地址xyz的内存”。抱歉格式不佳。

更新 我在SPOJ上得到了一个错误的答案,我检查了样本测试用例。有人可以帮助我找出需要处理的棘手案件吗?我认为这与空白行有关!如何跳过空白输入行? http://ideone.com/XUG4kS  :(

#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <sstream>
using namespace std;

int main()
{
    int Z;
    cin>>Z;

    /* **This condition leads to a segmentation fault, if I remove
       this condition, the code runs fine. I tried using a 
       for-loop to accept input N number of times but that
       didn't work either. So if I remove this Z loop, 
       my program works**! */   
    while(Z--) 
    {
        string s;
        getline(cin, s);
        istringstream iss(s);
        vector<string> numbers;

        do
        {
            string sub;
            iss >> sub;
            numbers.push_back(sub);
        } while (iss);

        // cout<<numbers[0]<<endl;
        // cout<<numbers[2]<<endl;;
        //cout<<numbers[4]<<endl;
        string a = numbers[0];
        string b = numbers[2];
        string result = numbers[4];
        int expression=0; int i=0;

        while(a[i]!='\0')
        {
            if(a[i]=='m')
                { expression=1;  break;}
            i++;
        }

        // cout<<i;
        // a[i]='x';
        // a.erase(i+1, i+7);
        // cout<<a;
        i=0;

        while(b[i]!='\0')
        {
            if(b[i]=='m')
                {expression=2;  break;}
            i++;
        }

        i=0;

        while(result[i]!='\0')
        {
            if(result[i]=='m')
                {expression=3;  break;}
            i++;
        }
        // cout<<expression<<endl;

        switch( expression )
        {
            int temp1, temp2;
            case 1:
                temp1 = atoi(result.c_str());
                temp2 = atoi(b.c_str());
                cout<<temp1-temp2<<" + "<<b<<" = "<<result<<endl;
                break;

            case 2:
                temp1 = atoi(result.c_str());
                temp2 = atoi(a.c_str());
                cout<<a<<" + "<<temp1-temp2<<" = "<<result<<endl;
                break;

            case 3:
                temp1 = atoi(a.c_str());
                temp2 = atoi(b.c_str());
                cout<<a<<" + "<<b<<" = "<<temp1+temp2<<endl;
                break;

        }
    }

    return 0;
}

0 个答案:

没有答案