Hey there all, long time lurker, this is my first post!! This is an assignment I have. Just need someone to look over this and tell me what I'm doing wrong!! I'm to read in a complex number (eg: 12 - i) and store the real and imaginary parts into different variables.
It stores the real part just fine but can not store the imaginary part properly. There are a few cases that happen when I run the code as it is now.
Case 1:
If user enters 12 + i and I stored the two parts into variables named 'a' (for the real part) and 'b'(for the imaginary part)
a will hold '12'
b will also hold '12'
Case 2:
If user enters any single digit number before 'i' in the complex number like 12 + 3i
a will hold '12'
b will hold '32'
the digit before 'i' is stored in the first position but the number in the second position does not change (in this case '2')
Case 3:
This is the only case where it runs properly. If the user enters a number that is two or more digits in front of 'i' in the complex number like 12 + 123i
//initializing everything to 0 or an empty string just to be safe
string s = "", temp1 = "", temp2 = "";
double a = 0, b = 0, x = 0;
int j = 0;
char c;
bool f = 0;
cout << "Enter your formula for complex numbers\n";
getline(cin,s);
for(int i = 0; i < s.length(); i++) //loops through user input for real part
{
if(s[i] >= '0' && s[i] <= '9')
temp1[i] = s[i];
else
{
x = i; //stores position being read in string when breaking out to be referenced by next loop
break;
}
}
a = atof(temp1.c_str());//converts string into float stores into a
for(int i = x; i < s.length(); i++) //loop to read for empty space, + or -
{
if(s[i]=='-') //checks for negative number
{
f=1;
x++;
break;
}
elseif(s[i]=='+')
{
x++;
break;
}
else
x++; //increments position in string currently being read to be referenced by next loop
}
for(int i = x; i < s.length(); i++) //reads for imaginary part!!!
{
if(s[i] >= '0' && s[i] <= '9')
{
temp2[j] = s[i]; // if digit is read stores digit into temp2 string
j++;
}
elsebreak;
}
b = atof(temp2.c_str()); //converts temp2 string into float
In lines 42 to 44 you did not follow your own comments to check for + - or space. Check for the space and if not a space, break but do not increment x.
You just got another digit instead of a space.
Hey thanks! I actually got it to work before I looked at your comment and did that exact same thing. sometimes it just takes looking at it for HOURS and messing around with it until you get the right thing. Thanks a lot!