Parsing a complex number - c++

I am trying to take a complex number input from the user in a form of a char or string like:
88.90-55.16i or -3.67+5i
and then convert it to float keeping the same format as above. Not (x,y).
char user[100];
vector < float > V;
for (int y = 0; y < 5; y++)
{
cout << "Enter a complex number:" << endl;
cin >> user;
float newfloat = atof(user);
cout << newfloat << endl;
}
Currently its not converting the whole number. Just 88 or -3 from above input examples.

You would need to store the real and imaginary components of the complex number in separate float variables, which may or may not be grouped using a struct/class or std::pair<>. Input should be something like this:
std::cout << "Enter a complex number:\n";
float real, imaginary;
char i;
if (std::cin >> real >> imaginary >> i && i == 'i')
{
...do something with real & imaginary...
}
else
{
std::cerr << "unable to parse input as a complex number\n";
exit(1);
}
(FWIW, this is very obviously related to this earlier question - either the same person using a new username, or someone doing the same assignment. I provide an example program using std::complex<> in my answer there.)

Float is not capable of storing that type of number. A float is designed to hold a single floating point number, i.e. 10.3 or 5.2. Not 1+2i. That is a two-dimensional quantity.
I would recommend you use the complex<float> template for your data type or create your own class. Look here for more: https://msdn.microsoft.com/en-us/library/5de6f0bw.aspx about the complex<float> It comes with built in tools to convert strings to complex types.

I have never used C++ before but I am sure float does not fit your expectations. Imaginary number is not a subset of float so you can't do that.
I guess one possible solution is to write your own imaginary class, or use a build-in one if there is one.
Also write a fromString()/toString() in your custom imaginary class.

Related

Calculate using int and output float?

//findSlope(twoPoints).exe
//finding the slope of line AB, using coordiantes of point A and B.
#include <iostream>
int main()
{
int a, b, c, d;
float answer;
std::cout << "The X coordiante of A: ";
std::cin >> a;
std::cout << "\nThe Y coordiante of A: ";
std::cin >> b;
std::cout << "\nThe X coordiante of B: ";
std::cin >> c;
std::cout << "\nThe Y coordiante of B: ";
std::cin >> d;
std::cout << "\nThe slope of line AB = " << std::endl;
answer = (b-d)/(a-c);
std::cout.setf(std::ios::fixed);
std::cout.precision(3);
std::cout << answer << std::endl;
//alternative= std::cout << fixed << setprecision(#) << answer << std::endl;
std::cout.unsetf(std::ios::fixed);
return 0;
}
I am learning C++ and I tried to code a program that calculate the slope using the coordinates of two points.
I understand that if I use float for variables I declared for the coordinates, the result of the calculation would output as float with decimals. However, I wonder if I may still use int for user input so that I can ensure the inputs are integers.
Extra question: Would it be possible to convert a float presented in the form of "#.##" to "# #/#"? More like how we do mathematics IRL.
You can use implicit conversion to double:
answer = (b-d)/(a-c*1.0);
Or explicit cast:
answer = (b-d)/(a-(float)c);
Bonuses:
for the fraction part: Converting decimal to fraction c++
Why does integer division result in an integer?
You can use int for user input, but to precisely calculate anything that contains a division operator /, you'll need to cast to floating point types.
It's usually considered a good practice in C++ to use static_cast for that (although you still may use c-style (float) syntax).
For example:
answer = static_cast<float>(b - d) / (a - c);
Here, you convert (b - d) to float and then divide it by integer, which results in a float.
Note that the following wouldn't work correctly:
answer = static_cast<float>((b - d) / (a - c));
The reason is that you first divide an int by another int and then convert the resulting int to a float.
P. S. float is really inaccurate, so I would advise to use double instead of float in all cases except where you want to write faster code that does not depend on mathematical accuracy (even though I'm not sure it would be faster on modern processors) or maintain compatibility with an existing library that uses float for some of its functions.

Reading the variables of another function

Let me introduce how I got this problem... Well, I know a little bit of FORTRAN, and now I'm learning C++.
While I read the beginnings, I'm (re)creating an old program that I have written in FORTRAN.
It do the calculation part of the topography surveying of a closed polygonal.
Well, I'm reading the book "Programming: Principles and Practice Using C++", and it says that in C++, we'd prefer to let each functions do the minimum number of things. For now, I have something like this (I ignored all the other functions):
int main(){
//Starting the program and reading all variables
try
{
//Program beginning
cout << "Hello. Welcome to the 'Topography Program'\n\n\n";
//Reading all the information needed
reading_is_fundamental();
//Testing the angular tolerance
ang_tolerance_test (number_of_points); } ...there's more subroutines' calls
catch (runtime_error& e)
{
cerr << "error:" << e.what()<<'\n';
return 1;
}
return 0;}
The "reading_is_fundamental()" is the call of a subroutine. There, I read all the information needed. My problem is lying on the second subroutine, "ang_tolerance_test (number_of_points)".
In FORTRAN, I abused too much of global variables, and now, in this book, says that we must avoid global variables.
End of story, I have two questions:
1 - This logic is correct or I misunderstood the book? Should I put some calculations (or at least the reading of the input variable, as they will appear in all the subroutine) in the main function or should I use it only to call my subroutines?
2 - If this is really the way that we should do in C++ (separate each action in one function), can somebody explain me how to grab variables that was written in the first subroutine and send to the others, like the "ang_tolerance_test" one?
Many thanks in advance!
EDIT
The function "reading_is_fundamental()" is where I read all the values by keyboard. I know how to read the values by a text file in FORTRAN and, in this case, it is a great advantage, as there are so many numbers to be read. But, I don't know yet how to do this in C++, so, please, ignore that I'm reading a lot of variables by keyboard, I'm studying it yet! Actually, doesn't really matter the way that I'm reading the variables, the point is that I want those doubles, int and vectors in the others soubroutines...
Well, this is "reading_is_fundamental:
//This subroutine reads all the variables
void reading_is_fundamental (){
cout << "What is the linear tolerance?\n";
double lin_tolerance;
cin >> lin_tolerance;
cout << "\nHow many points did you study?\n";
int number_of_points;
cin >> number_of_points;
cout << "\nWhat's the distance between each point?\n";
vector <double> distances;
for (double dist; cin >> dist;)
distances.push_back(dist);
if (distances.size() != number_of_points) error ("The number of distances must be equal to the number of points");
cout << "\nWhat's each horizontal degree angle?\n";
vector <double> horizontal_degrees;
for (double horizontal_degree; cin >> horizontal_degree;)
horizontal_degrees.push_back(horizontal_degree);
if (horizontal_degrees.size() != number_of_points) error ("The number of angles must be equal to the number of points");
cout << "\nWhat's each horizontal minute angle?\n";
vector <double> horizontal_minutes;
for (double horizontal_minute; cin >> horizontal_minute;)
horizontal_minutes.push_back(horizontal_minute);
if (horizontal_minutes.size() != number_of_pointsint) ("The number of angles must be equal to the number of points");
cout << "\nWhat's each horizontal second angle?\n";
vector <double> horizontal_seconds;
for (double horizontal_second; cin >> horizontal_second;)
horizontal_seconds.push_back(horizontal_second);
if (horizontal_seconds.size() != number_of_points) error ("The number of angles must be equal to the number of points");
cout << "\nWhat's the first azimuth degree?\n";
double first_az_degree;
cin >> first_az_degree;
cout << "\nWhat's the first azimuth minute?\n";
double first_az_minute;
cin >> first_az_minute;
cout << "\nWhat's the first azimuth second?\n";
double first_az_second;
cin >> first_az_second;
cin >> number_of_points;}
One thing that I din't know when I was writting this is if it's correct to put void in this function. My way of thinking is taht I don't want one return, but some variables filed.
The second function is the "ang_tolerance_test()". It is not ready yet, so, I will not copy here. The thing is that when I call this function in main(), I want to put the argument of it one value sent from "reading_is_fundamental()" (that is "number_of_points).
I hope this made my questions more clearly.
Try returning value from reading_is_fundamental function, which you could pass it to other function like:
int number_of_points = reading_is_fundamental();
//Testing the angular tolerance
ang_tolerance_test (number_of_points);
And define function like:
int reading_is_fundamental() {
....
return number;
}
Define a class like:
class Record
{
private:
double lin_tolerance;
int number_of_points;
public:
int getNumberOfPoints() { return number_of_points; }
void setNumberOfPoints(int v) { number_of_points = v; }
double getLinTolerance() { return lin_tolerance; }
void setLinTolerancedouble v) { lin_tolerance = v; }
};
And when you read the values, create an instance of Record, keep populating the values within record and at the end return that value so that you could pass it to ang_tolerance_test. Just similar to int above instead now you will get Record object from the function.

How to show float if the user inputs a digit with a decimal and int if the user inputs a whole number using function overloading

I am currently studying C++ by watching bucky's C++ tutorial.
In the tutorial he shows how to use function overloading
but the variables values of a and b are fixed in his tutorial video.
I'm wondering what happens if the user needs to input something (decimal or whole number)
and how to make the program identify whether the input data is an int or an float.
here is the code in the tutorial video:
#include <iostream>
using namespace std;
void printnumber(int x){
cout << "I am printing an integer " <<x << endl;
}
void printnumber(float x){
cout << "I am printing an float: " << x << endl;
}
int main(){
int a = 54;
float b= 32.4896;
printnumber(a);
printnumber(b);
}
While here is the code I created:
#include <iostream>
using namespace std;
int a;
float b;
void printnumber(int x){
cout << "I am printing an integer " <<x << endl;
}
void printnumber(float x){
cout << "I am printing an float: " << x << endl;
}
int main(){
cout << "enter a whole number or a number with decimal: ";
cin >> ; //what will i put here?
printnumber(a);
printnumber(b);
}
This is not as trivial as one would think. One way could be to read the input as a string, and see if the string contains a decimal-point (which would cause problems on locales where the decimal-point is a comma instead).
Another solution is to read as a string, then try to convert it to a floating point value, and if that fails then convert it to an integer.
I would recommend the last method.
Or for simplicity's sake, just instruct the user to input an integer followed by a floating point value:
int a;
std::cout << "Enter an integer value: ";
std::cin >> a;
float b;
std::cout << "Enter a floating point value: ";
std::cin >> b;
Then hope that the user actually enters correct values.
You do not get the data until runtime, so you can't know the type at compile time, which is when the function overload is determined. Thus, you need to make some decision at runtime.
I suggest you look up my most favorite C++ book of all time, Advanced C++ Programming Styles and Idioms by Jim Coplien. Pay careful attention to the letter/envelop idiom, which describes how to accomplish what you want.
It may be overkill for this simple example, but it's worth learning since you are hunting for knowledge.
You will get a std::string back from cin which you will need to convert to the appropriate type once you detect if it has a dot or not.
std::string user_input;
cout << "enter a whole number or a number with decimal: ";
cin >> user_input;
if(user_input.find('.') != std::string::npos){
// we found a float (probably)
// uses boost library to make stuff easier
printNumber(boost::lexical_cast<float>(user_input));
}else{
printNumber(boost::lexical_cast<int>(user_input));
}
instead of boost::lexical_cast you can also use std::stringstream
std::stringstream ss;
ss << user_input;
if(user_input.find('.') != std::string::npos){
// we found a float (probably)
float f;
ss >> f;
printNumber(f);
}else{
int i;
ss >> i;
printNumber(i);
}
Joachim is right that this isn’t trivial. The “proper” way to do this is to use a parser.
Writing such a parser isn’t too hard – it just needs to check that the number is in the right format, by trying to read it as either type and retrying if it doesn’t work. A “cleaner” solution is to use a formal parsing framework such as Boost.Spirit.Qi.
Here’s a straightforward (but somewhat convoluted) solution:
int main() {
std::string value;
std::cin >> value;
std::size_t end;
int intval = std::stoi(value, &end);
if (end == value.size())
printnumber(intval);
else
printnumber(std::stof(value));
}
This checks that std::stoi converted the whole string rather than just parts of it.
Notice that this solution is not very robust since it does no proper error checking. In a real application I would strongly recommend going the Boost.Qi way because it makes the code simpler and more robust, but it requires some deeper C++ knowledge.
For reference, the “proper” solution using a parsing framework would look something like this:
struct printer : boost::static_visitor<void> {
template <typename T>
void operator ()(T const& value) const { printnumber(value); }
};
int main() {
std::string value;
std::cin >> value;
namespace qi = boost::spirit::qi;
auto begin = std::begin(value);
auto const end = std::end(value);
boost::variant<int, float> result;
bool success = qi::parse(begin, end, (qi::int_ >> !qi::lit('.')) | qi::float_, result);
if (not success or begin != end)
std::cerr << "Something went wrong\n";
else
apply_visitor(printer{}, result);
}

How do I make a program using 3 overloaded functions (difference in parameters is int, long, float) meanwhile only asking one input entry?

I have to write a program where I put in two numbers and the program calculates the average. I want to write my program so that if I input two decimal numbers, the program will call the float function, and if I input two integer numbers it will call the integer function, input two long numbers, it will call long function.
The main problem I am having is choosing the variable type. Because if I use a long type for my variable, but the two numbers input by the user are decimal, then the program calls the long function and the average comes out as a long variable.
Here is what I've got so far:
#include <iostream>
int average(int, int);
long average(long, long);
float average(float, float);
int main()
{
//The variables
// The problem with them is that if I use
// a type, let's say int, but the input
// is a float, then it won't work
x;
y;
averag;
std::cout << "Here is a number: ";
std::cin >> x;
std::cout << "\nHere is another one: ";
std::cin >> y;
//The function in call
averag = average(x, y);
std::cout << "\n\nHere is the average: ";
std::cout << averag;
return 0;
}
//The definition of the int function
int average(int x, int y)
{
int x;
int y;
int average;
average = (x + y) / 2;
return average;
}
// The definition of the short function
short average(short x, short y)
{
short x;
short y;
short average;
average = (x + y) / 2;
return average;
}
// The definition of the float function
float average(float x, float y)
{
float x;
float y;
float average;
average = (x + y) / 2;
return average;
}
//I think i'm not grasping the scopes in which I can define a variable
//and where I must define the parameters within the functions
I think that defining the type variables in each function scope is wrong, but how else am i supposed to define the variables!
How to do that ?
I would have the user input the type first (e.g. 'Enter F for float, I for integer...' etc) then using that input as a condition, read the input into the appropriate type of variable and call your overloaded average function.
Yes, defining the variables in the function scope the way you have is wrong. Your parameters are defining the variables, defining them in the function will just define them again. I'm not the most familiar with c++, but I think that will "shadow" the parameter variables, and your calculations will not work.
For the main question, I agree with sje397's answer, have the user input the type of average they want to perform first. If the user enters 5 and 4, the double average will be different than the long average.
I would input the value as a string and then use successive calls to boost::lexical_cast to infer a type:
std::string x,y;
std::cin >> x >> y;
try {
short averag = average(boost::lexical_cast<short>(x), boost::lexical_cast<short>(y));
std::cout << averag << "\n";
return;
} catch(boost::bad_lexical_cast&) {}
try {
int averag = average(boost::lexical_cast<int>(x), boost::lexical_cast<int>(y));
std::cout << averag << "\n";
return;
} catch(boost::bad_lexical_cast&) {}
try {
float averag = average(boost::lexical_cast<float>(x), boost::lexical_cast<float>(y));
std::cout << averag << "\n";
return;
} catch(boost::bad_lexical_cast&) {}
std::cout << "Oops\n";
I'd probably not use this form, however. I'd probably factor out the common code into a function template.
You could ask the user which calculation he wants to perform.
Drawbacks:
Internals of the program which are of no interest to the user, are exposed (the user wants to calculate the average of two numbers).
You cannot trust the user. If your program is robust and doesn't crash (for example if the user types in decimal numbers after choosing the integer calculation), it may produce wrong results
I reccomend to read in the input each time and look if the value is a decimal number, a short integer (less than 9 digits) or a long integer. Then you have to consider a few cases (for example one input is decimal, the other a long integer) and to perform the calcuation. It's quite low-level, but I would it refactor out into a function anyway.

Matrix multiplication with vectors - C++

I am working on making a program that can multiply matrices of user-defined size. I use vectors to store the values in the matrix.
void Multiply(vector<float> A,vector<float> B,int rA, int cA,int rB,int cB)
{
system(CLEARSCREEN);
vector<float> C; // The resulting matrix
int sizeA=rA*cA;
int sizeB=rB*cB;
int sizeC=rA*cB;
int lrA=sizeA-1;
int lrB=sizeB-1;
int writeHead=0;
A.resize(sizeA);
B.resize(sizeB);
C.resize(sizeC);
demoDisplay(rA,rB,cA,cB,lrA,lrB,sizeA,sizeB);
for(;writeHead<=lrA; writeHead++)
{
cout << "Please enter a value for \"" << alphabet[writeHead] << "\" in MATRIX A.\n";
cin >> A[writeHead];
}
cout << "\n";
writeHead=0;
for (;writeHead<=lrB; writeHead++)
{
cout << "Please enter a value for \"" << alphabet[writeHead] << "\" in MATRIX B.\n";
cin >> B[writeHead];
}
cout << "\n\n";
displayMatrices(A,B,rA,rB,cA,cB,lrA,lrB,sizeA,sizeB);
for (int colRead=0; colRead<=cA; colRead++) {
// somehow iterate through each element of the vector?
}
}
I'm relatively new to C++, and so I'm not quite sure how to do the actual multiplication of the two matrices. If anyone could help, it would be great.
Maybe you were mislead by the name of the vector container, that implies some mathematical use. The vector template doesn't provide any function to multiply matrices or even to multiply vectors. The vector in this case only provides you with a container to store a matrix. Obviously you store the matrices in some linearized way and that will make the multiplication more complicated later.
Be sure to read http://www.cplusplus.com/reference/stl/vector/
Furthermore you dont really want to iterate through the vectors, because if that was the case, you could have just used some other container. You want random access to do multiply the columns and rows by hand. For this you can use the []-operator] or the at() member function.
Then it is just a matter of doing the multiplication by hand, as for example shown here(which also includes some pseudo code).