Vectors, Pointers, Classes and EoF Loops (C++) - c++

I am trying to get a vector to store objects of class 'Complex'.
This is how I have tried to get it to store:
ifstream values;
values.open("h://values.txt");
if(!values)
{
cout<<"Error: cannot open "<<"values.txt"<<endl<<endl;
}
else
{
//Initialise list
vector<Complex> v;
Complex *c1;
double a,b,d=0,e=0;
char c;
int count=0;
while(values)
{
values>>c>>a>>b;
c1=new Complex;
v.push_back(*c1);
cout<<c<<" "<<a<<" "<<b<<endl;
switch (c)
{
case 'r':
case 'R':
case 'p':
case 'P':
{
//Call constructor
v[count].setType(c);
switch (c)
{
case 'r':
case 'R':
{ v[count].setReal(a);
v[count].setImaginary(b);
v[count].topolar(a,b,d,e);
break;
}
case 'p':
case'P':
{ v[count].setLength(a);
v[count].setAngle(b);
v[count].frompolar(d,e,a,b);
break;
}
default:
{ cout<<"Type Error"<<endl;
break;
}
}
count++;
break;
}
default:
{
//error message
cout<<" Failed input type, ensure all of type 'r' or 'p'"<< endl;
cout<<"Programme Closing"<<endl;
break;
}
};
}
While this will read the info in my programme, it insists on reading the last line twice (I put the cout into this loop so it was easier to see what numbers were where). I have tried using a for loop, but because I want it to run till the end of file I think I have to use a while loop, but I might be wrong.
My supervisor said something along the lines of c1 being overwritten on every loop, but I thought this should be OK on the basis the information is passed to the vector before it is overwritten by the next line so I'm a bit confused.
The next problem is that when I then try and print out all the information again, outside of the loop shown above (for example to allow for manipulation before printing) it prints the same thing over and over until the for loop reaches the count...
int y;
int z;
while(y!=3)
{
cout<< " What would you like to do?"<<endl;
cout<< " Type the number of the option you would like"<<endl;
cout<< " 1. Show all numbers in polar form"<<endl;
cout<< " 2. Show all numbers in rectangular form"<<endl;
cout<< " 3. Show all numbers in both forms"<<endl;
cout<< " 4. Convert a number to its conjugate"<<endl;
cout<< " 5. Exit"<<endl;
cin>>y;
switch(y)
{
case 1:
for(z=0; z<count;z++)
{
v[z].getLength();
v[z].getAngle();
cout<< a<<" "<<b<<endl;};
break;
case 2:
for (z=0; z!=count;z++)
{
v[z].getReal();
v[z].getImaginary();
};
break;
case 3:
cout<<" Real Imaginary | Length Angle | Original Type"<<endl;
for(z=0; z!=count;z++)
{ v[z].getLength();
v[z].getAngle();
v[z].getReal();
v[z].getImaginary();
cout<<a<<" "<<b<<" "<<d<<" "<<e<<endl;
In case any of you try to run the programme:
#include "Class definitions.h"
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string.h>
#include <cmath>
#include <vector>
using namespace std;
Any help will be greatly appreciated!!
Thanks muchly!
H
x

Whether input succeeds is only known after the input, not before. After you do
values>>c>>a>>b;
you use the values, even if the input has failed (e.g. because of end of file). Put the test in the condition of the while loop:
while ( values >> c >> a >> b )
and your code should work. (Whether this is the best way to handle the problem is another question. I'd probably use std::getline(), followed by std::istringstream to parse the line I'd read. Much easier error recovery.)

Related

c++ obect out of scope inside a switch statement

The object derm is out of scope in the switch statement.
I tried to make it a static member function.
Is there anyway I can make this work?
Here is my code:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <ctime>
using namespace std;
class Invinq {
int menu_pick;
string db_read_out;
public:
Invinq();
void menu_maker();
int add_record();
int change_record();
int delete_record();
int display_record();
int exit_program();
};
Invinq::Invinq()
{
cout <<"Welcome to Inventory Inquisator.\n********************************\n" << endl;
ifstream db_invinq;
db_invinq.open("Invinq_db.txt");
if(!db_invinq)
{
cout<<"\nNot able to create a file. MAJOR OS ERROR!! \n";
}
for(int i = 0; i < db_invinq.eof(); i++)
{
db_invinq >> db_read_out;
cout << db_read_out;
}
}
//Menu maker
void Invinq::menu_maker()
{
cout << "1. Add Record\n2. Change Record\n3. Delete Record\n4. Display Record\n5. Exit\n\nPick One: ";
cin >> menu_pick;
switch(menu_pick)
{
case 1: derm.add_record(); break;
case 2: derm.change_record(); break;
case 3: derm.delete_record(); break;
case 4: derm.display_record(); break;
default: cout << "Pick a number between 1-5, try again\n";
}
derm.menu_maker();
}
int main() {
Invinq derm;
derm.menu_maker();
return 0;
}
You seem to have completely missed the point. you don't need derm when you are already inside the Invinq class - just call menu_maker().
Having said that: you are using recursion for no good reason. This can have some unexpected side effects. I suggest you refactor menu_maker() - if fact right now there is no way to get out of the recursion, so that is really bad!
You main should have the loop and create a Invinq each time through, otherwise you are just overwriting the same object each time which is probably now what you want.
Inside the definition of your class method, you should refer to yourself using the keyword this.
Replace all the method calls as following:
case 1: derm.add_record(); break; > case 1: this->add_record(); break;
Note: this returns a pointer to your object, this is why we use -> rather than .

Code stops/ends after each case selected in nested switch and error C4244 conversion from double to float in c++

I have made a calculator( code below ) and it seems to run smoothly, except for 6 C4244 errors which don't seem to effect the way it runs. The only problem that I have now is that after you select any case, the program runs that part of the case and exits, but I want it to return to the main switch after it runs the case selected.How can that be done and why am i getting the errors?
void main(void)
{
int c;
printf("Enter the number of the type of operation you would like to perform:\n\n");
printf("1.Basic Mathematical Operations\n2.Trignometric Operations\n3.Quadratic Operations\n4.Lograthimic Operations\n5.Matrix Operations\n\nNumber selected: ");
scanf_s("%d",&c);
switch(c)
{
case 1:
int m;
printf("\n\nEnter the number of the operation you would like to perform:\n");
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n5.Exponent\n6.Square Root\n7.Inverse\n\nNumber selected: ");
scanf_s("%d",&m);
switch(m)
{
case 1:
add();
break;
case 2:
sub();
break;
case 3:
mul();
break;
case 4:
div();
break;
case 5:
exp();
break;
case 6:
sqrt();
break;
case 7:
inv();
break;
}
break;
}
One of the C4244 errors is in the following function,in the line "r=sin(a*Pi/180.0);" and the function is called in another nested switch case:
void sind(void)
{
float a, r;
printf("enter angle");
scanf_s("%f",&a);
r=sin(a*Pi/180.0);
printf("The sine of %f degrees is %f.\n", a, r );
_getch();
}
Your conversion error of double to float is most likely due to the use of 180.0 which is automatically interpreted as double. You have to add an 'f' as suffix to specify a float like this 180.0f. Also you have to pay attention to your declaration of 'Pi' which should also be a float number.
You asked two questions, so I don't know which one is relevant to your post. However, I will answer the one where you are having trouble getting the code to go back to the beginning to request subsequent choices to the user.
The easiest way to accomplish the loop is to break up your code into functions. Having switch statements that are so many lines long is not maintainable, and the logic gets all lost.
Also, the main() function returns int, not void.
For example:
#include <iostream>
using namespace std;
int promptAndGetOperation()
{
int op;
cout << "Enter the number of the type of operation you would like to perform:\n\n";
cout << "1.Basic Mathematical Operations\n2.Trignometric Operations\n3.Quadratic "
"Operations\n4.Lograthimic Operations\n5.Matrix Operations\n\n"
"6. Exit\n\nNumber selected: ";
cin >> op;
return op;
}
void performOperation(int op)
{
// fill this in
}
int main(void)
{
int operation;
do
{
operation = promptAndGetOperation();
if ( operation >= 1 && operation <= 5)
performOperation(operation);
else
if ( operatiom < 1 )
cout << "Illegal operation. Try again\n\n";
}
while (operation != 6 );
}
This is a basic skeleton of what you should be doing. See how simple the main program becomes? The do-while loop is the main driver.

Make a charcter mean an operator c++

I am trying to write a program that takes two numbers and allows the user to input either a, s, m, or d. Basically what I am trying to do is make the characters mean addition, subtraction, multiplication and division respectively. The problem is though is I am unsure of how to do it. Here is the code I have so far.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
char operation;
cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;
Check the switch statement:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double num1;
double num2;
char operation;
cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;
switch(operation)
{
case 'a':
... // Addition code
break;
case 's':
... //Substraction code
break;
...
}
You could also just use if and else, one for each type of operation.
Also, just as a tip, consider validating your input data (try typing more characters into your program, or invalid options).
You use a switch:
switch (operation) {
case 'a': // addition
break;
case 's': // subtraction
break;
// ...
default: // none of these
break;
}

C++ prototypes not being redefined

I am a beginner in programming and am just starting to write programs that are complex enough where prototypes would be helpful. The problem is when I write my program, compile and run it the functions that are prototyped are blank so none of my cout or cin
prompts in the later defined functions appear.
In this code there is only one portion of the switch statement done in which the CubeVol function is prototyped and then later defined.
This code does compile and when it is run it shows the menu. When I type "2" the program ends without couting "length of cubes side" or asking for an input.
if it matters, I'm using Cygwin with gnu g++ compiler and notepad++ to write the code, which is saved as a .C file. I've also tried formatting it as a .cpp
Keep in mind that the mostly blank switch statement is for later when I actually finish the program.
how do i prototype the CubeVol Function Correctly?
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
double CubeVol();
int main()
{ int choice=0;
cout<< " 1. Sphere \n 2. Cube \n 3. Cone \n 4. Cylinder \n 5. Prism \n 6. Exit \n";
cin>> choice;
switch (choice){
case 1:
;
break;
case 2:
CubeVol;
break;
case 3:
;
break;
case 4:
;
break;
case 5:
;
break ;
case 6:
;
;
break;
};
}
double CubeVol ()
{
double side=0.0; double cubev=0.0;
cout<< "length of cubes side";
cin>> side;
cubev= pow(side,3);
return cubev;
}
You are not calling the function CubeVol() in case 2:
case 2:
std::cout << CubeVol() << "\n"; //call the function and print return value
break;
Also the return value is not being utilized.

_getch not reading input into variable

I'm having trouble with the _getch() function, I want it so that the user does not need to hit ENTER when selecting things from the menu. However, when I try and use it, it either doesn't input the data into a variable, or it skips over the switch I have. I'm using Windows 7, and the CodeBlocks IDE. What am I doing incorrectly? Thanks in advance.
#include <iostream>
#include <sstream>
#include <conio.h>
using namespace std;
stringstream ss;
int a;
void play()
{
cout << "\nYou wake up on the forest floor. You do not remember where you are, who you are, or anything\nthat has happened before you waking up. You seem to be some type of...\n";
cout << "--CHARACTER SELECTION--\n1. Warrior\n2. Mage\n3. Rouge";
cin.get();
};
int main()
{
// CreateDirectory()
cout << "--SELECTION MENU--\n1. Begin\n2. Delete Game\n3. Instructions" << endl;
a=_getch();
switch(a){
case 1:
play();
break;
case 2:
// delete();
break;
case 3:
// help();
break;
return 0;
}
}
Compare your char against the characters '1', '2' and '3' rather than the integers 1, 2 and 3.
switch(a){
case '1':
play();
break;
case '2':
// delete();
break;
case '3':
// help();
break;
return 0;
}