I have a strange problem. Whenever I add an extra loop to run for T times, it causes a segmentation fault. I'm trying to solve this problem: http://www.spoj.com/problems/ABSYS/ So if I enter the input test cases one by one, it produces the correct output. However when I try to accept input for T number of times, it leads to a segmentation fault. I tried to debug and it says "s cannot access memory at address xyz". Sorry for the poor formatting.
Update: I'm getting a Wrong Answer on SPOJ, and I've checked the sample test cases. Can someone help me in finding out which tricky cases need to be taken care of? I think it's got to do with blank lines! How can I skip blank input lines? 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;
}