C++ Beginner : I can't fix&compile the code - c++

I have been started C++ lessons in my University since 3 weeks, so I'm quite beginner.
I have 4 codes to find the errors and fix them, 2 of them are done, but i couldn't figure out why did not the other 2 get compiled.
There's the first code;
#include <cstring>
#include <iostream>
#include <climits>
#include <cfloat>
#include <cmath>
using std::cout;
using std::endl;
template<class T>
void to_bin(T v)
{
union
{
T value;
unsigned char bytes[sizeof(T)];
};
memset(&bytes, 0, sizeof(T));
value=v;
// assumes little endian machine
for (size_t i = sizeof(T);i>0;i--)
{
unsigned char pot=128;
for (int j = 7;j>=0;j--,pot/=2)
if (bytes[i-1]&pot)
cout << "1";
else
cout << "0";
cout << " ";
}
cout << endl;
}
int main() {
cout <<" Binaerdarstellungen von -2, -1, 0, 42, INT_MAX und INT_MAX+1 als Int: " << endl;
int p_i = (-2), q_i=-1,r_i=0,s_i=42,t_i=INT_MAX,u_i=INT_MAX+1 ;
cout << "Fuer -2: ";
to_bin(p_i);
cout << endl;
cout << "Fuer -1: ";
to_bin(q_i);
cout << endl;
cout << "Fuer 0: ";
to_bin(r_i);
cout << endl;
cout << "Fuer 42: ";
to_bin(s_i);
cout << endl;
cout << "Fuer INT_MAX: ";
to_bin(t_i);
cout << "Fuer INT_MAX+1: ";
to_bin(u_i);
cout << endl;
cout << endl << "Binaerdarstellungen von -2.0, 1.0, 0.0, 42.0, FLT_MAX, FLT_MAX+1 als float: " << endl;
float p_f = -2.0, q_f= -1.0,r_f=0.0,s_f=42.0,t_f=FLT_MAX,u_f=FLT_MAX+1 ;
cout << "Fuer -2.0: ";
to_bin(p_f);
cout << endl;
cout << "Fuer -1.0: ";
to_bin(q_f);
cout << endl;
cout << "Fuer 0.0: ";
to_bin(r_f);
cout << endl;
cout << "Fuer 42.0: ";
to_bin(s_f);
cout << endl;
cout << "Fuer FLT_MAX: ";
to_bin(t_f);
cout << endl;
cout << "Fuer FLT_MAX+1: ";
to_bin(u_f);
cout << endl;
cout << endl << "Binaerdarstellungen von -2.0, 1.0, 0.0, 42.0, DBL_MAX, DBL_MAX+1 als double: " << endl;
double p_d = -2.0, q_d=-1.0,r_d=0.0,s_d=42.0,t_d=DBL_MAX,u_d=DBL_MAX+1 ;
cout << "Fuer -2.0: ";
to_bin(p_d);
cout << endl;
cout << "Fuer -1.0: ";
to_bin(q_d);
cout << endl;
cout << "Fuer 0.0: ";
to_bin(r_d);
cout << endl;
cout << "Fuer 42.0: ";
to_bin(s_d);
cout << endl;
cout << "Fuer DBL_MAX: ";
to_bin(t_d);
cout << endl;
cout << "Fuer DBL_MAX+1: ";
to_bin(u_d);
cout << endl;
cout << endl << "Groesse von Integer Variablen: ";
cout << sizeof(p_i) << endl;
cout << "Groesse von Gleitkomma Variablen mit einfacher Genauigkeit: ";
cout << sizeof(p_f) << endl;
cout << "Groesse von Gleitkomma Variablen mit doppelter Genauigkeit: ";
cout << sizeof(p_d) << endl;
return 0;}
and so the other one;
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
void to_bin(T v)
{
using std::cout;
using std::endl;
union
{
T value;
unsigned char bytes[sizeof(T)];
};
memset(&bytes, 0, sizeof(T));
value=v;
// assumes little endian machine
for (size_t i = sizeof(T);i>0;i--)
{
unsigned char pot=128;
for (int j = 7;j>=0;j--,pot/=2)
if (bytes[i-1]&pot)
cout << "1";
else
cout << "0";
cout << " ";
}
cout << endl;
}
int main() {
long unsigned int stack_field;
long unsigned int *heap_field = new long unsigned int;
short unsigned int *stack_pointer = (short unsigned int*)&stack_field;
short unsigned int *heap_pointer = (short unsigned int*)heap_field;
stack_field = 0;
*heap_field = 0;
*stack_pointer = 1;
*heap_pointer = 1;
stack_pointer = stack_pointer + 1;
heap_pointer = heap_pointer + 1;
to_bin(stack_field);
to_bin(*heap_field);
to_bin(*stack_pointer);
to_bin(*heap_pointer);
*stack_pointer = 1;
*heap_pointer = 1;
to_bin(stack_field);
to_bin(*heap_field);
to_bin(*stack_pointer);
to_bin(*heap_pointer);
// HIER EDITIEREN
cout << "stack_field " << sizeof(stack_field) <<" " << stack_field <<" "<< &stack_field << endl;
cout << "heap_field " << sizeof(heap_field) <<" " << *heap_field <<" "<< &heap_field << endl;
cout << "stack_pointer " << sizeof(stack_pointer) <<" " << *stack_pointer <<" "<< &stack_pointer << endl;
cout << "heap_pointer " << sizeof(heap_pointer) <<" " << *heap_pointer <<" "<< &heap_pointer << endl;
delete heap_field;
return 0;
}
What is the thing, that i'm doing wrong?
I only have 3 more hours to finish and upload it.
Thanks...
UPDATE
Errors of first code :
x#cluster:~/x/cppfiles[534]$ g++ -Wall -Werror -o aufgabe1 aufgabe1.cpp
cc1plus: warnings being treated as errors
aufgabe1.cpp: In function 'int main()':
aufgabe1.cpp:41: error: integer overflow in expression
aufgabe1.cpp: In function 'void to_bin(T) [with T = int]':
aufgabe1.cpp:44: instantiated from here
aufgabe1.cpp:17: error: unused variable 'value'
aufgabe1.cpp:17: error: unused variable 'bytes'
aufgabe1.cpp: In function 'void to_bin(T) [with T = float]':
aufgabe1.cpp:70: instantiated from here
aufgabe1.cpp:17: error: unused variable 'value'
aufgabe1.cpp:17: error: unused variable 'bytes'
aufgabe1.cpp: In function 'void to_bin(T) [with T = double]':
aufgabe1.cpp:97: instantiated from here
aufgabe1.cpp:17: error: unused variable 'value'
aufgabe1.cpp:17: error: unused variable 'bytes'
And errors of the second code:
x#cluster:~/x/cppfiles[534]$ g++ -Wall -Werror -o aufgabe4 aufgabe4.cpp
cc1plus: warnings being treated as errors
aufgabe4.cpp: In function 'void to_bin(T) [with T = long unsigned int]':
aufgabe4.cpp:48: instantiated from here
aufgabe4.cpp:15: error: unused variable 'value'
aufgabe4.cpp:15: error: unused variable 'bytes'
aufgabe4.cpp: In function 'void to_bin(T) [with T = short unsigned int]':
aufgabe4.cpp:50: instantiated from here
aufgabe4.cpp:15: error: unused variable 'value'
aufgabe4.cpp:15: error: unused variable 'bytes'

You probably get those eroors because of the -Wall (make gcc display "many" warnings) and -Werror (treat all warnings as errors).
So your code may compile fine if no special flags are given, but here you force adding warning and failing on them.
Fixing the code is then necessary:
for error: unused variable 'value' this is quite simple, just remove the useless variables.
For the overflow, check the value in order not to overflow (fix the code); my compiler points int u_i=INT_MAX+1 which is obviously overrflowing (you explicitly add 1 to the maximum value)
Note: adding -Wall -Werror is a good idea (IMHO) as it generally points coding errors or things that would improve your code.

Related

error: request for member ‘find’ in ‘sentence’, which is of non-class type ‘char*’ [duplicate]

This question already has answers here:
What is array to pointer decay?
(11 answers)
Array Size Member Function Compile Error
(3 answers)
Closed 15 days ago.
I get an error saying "'find' in ‘sentence’, which is of non-class type ‘char*’".
So the instruction was to enter a string and identify which in the string is a noun, pronoun, adjectives and a linking verb. Everything seems to work except the ".find" part. I really need help.
(btw, nvm the other unecessary things. I made the code shorter to put focus more on the problem)
#include <iostream>
#include <cstring>
#include <cctype>
#include <string>
using namespace std;
string student_id, first_name, last_name, middle_name, suffix;
char sentence[100][100];
char history1[100][100];
int h = 0, s= 0;
char noun[20][20] = {"Ervin", "Rafi", "Peco", "luis", "Edgar", "Benj", "Rias", "Aki", "Naruto", "Jhay", "Josh", "Jopay", "Sasuke", "Joshua", "Trump", "Benjo", "Alice", "Janelle", "Samantha", "Jairah"};
char pronoun[20][20] = {"he", "she", "i", "it", "you"};
char verb[20][20] = {"is", "was", "are", "as", "am"};
char adj[20][20] = {"big", "small", "racist", "fat", "Funny", "gay", "black", "white", "rainbow", "tiny", "smart", "bi", "pan", "stupid", "idiot", "buang", "retard", "gaymer", "special", "talented"};
void display_dictionary();
void open_checker();
bool hasElement(char sentence[], char elements[], int size);
int main()
{
int option;
cout << endl << "Account Menu" <<endl;
cout << "[1] Open checker" << endl;
cout << "[2] Display Dictionary" << endl;
cout << "Option: ";
cin >> option;
switch (option){
case 1: open_checker(); break;
case 2: display_dictionary(); break;
}
return 0;
}
void display_dictionary(){
cout << "List of Nouns: ( ";
for (int n = 0; n < 20; n++){
cout << noun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Pronouns: ( ";
for (int n = 0; n < 5; n++){
cout << pronoun[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Linking Verbs: ( ";
for (int n = 0; n < 5; n++){
cout << verb[n] << " " ;
}
cout << ")" << endl << endl;
cout << "List of Adjectives: ( ";
for (int n = 0; n < 20; n++){
cout << adj[n] << " " ;
}
cout << ")" << endl << endl;
}
void open_checker(){
int option;
cout << "Enter Sentence: ";
cin.ignore();
cin.get(sentence[s], 100);
if (hasElement(sentence[s], noun[s], 20)){
cout << " Is a noun." << endl;
}
if (hasElement(sentence[s], adj[s], 20)){
cout << " Is an Adjectives." << endl;
}
if (hasElement(sentence[s], verb[s], 5)){
cout << " Is a Linking Verb." << endl;
}
if (hasElement(sentence[s], pronoun[s], 5)) {
cout << " Is a Linking Verb." << endl;
}
else {
cout << "Sentence does not have all required elements." << endl;
}
strcpy(history1[h], sentence[s]);
history1[h][h] = sentence[s][s];
h++;
s++;
cout << "Type 1 to go back: ";
cin >> option;
if (option == 1){
main();
}
}
bool hasElement(char sentence[], char elements[], int size){
for (int i = 0; i < size; i++) {
if (sentence.find(elements[i]) != string::npos) {
cout << elements[i];
return true;
}
}
return false;
}```

how to use if else c++

How do you provide a condition in the if statement, if the variable is an integer data type then it will be displayed, and if the variable is any other data type then something else will be displayed?
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <conio.h>
using namespace std;
int main() {
char pilih,pilih2;
int p, l, a, t, r,ulang = 4;
float luas1, luas2, luas3, keliling1, keliling2, keliling3, phi = 3.14;
while (ulang > 0) {
pilihUlang:
cout << "Pilih jenis bangun datar berikut :\n 1. Persegi panjang\n 2. Segitiga sama sisi\n 3. Lingkaran" << endl;
cout << "Masukan pilihan anda [1/2/3] : ";
cin >> pilih;
system("cls");
switch (pilih) {
case '1':
system("color 07");
cout << "Luas Dan Keliling Persegi Panjang" << endl;
cout << "Masukan Panjang = ";
cin >> p;
if (?) { // <-- here
cout << "Masukan Lebar = ";
cin >> l;
system("cls");
cout << "Luas dan keliling Persegi Panjang dengan panjang " << p << " dan lebar " << l << ", yaitu :" << endl;
luas1 = p * l;
keliling1 = 2 * (p + l);
cout << "Luas = " << luas1 << endl;
cout << "Keliling = " << keliling1 << endl;
cout << "Sisa bisa memilih ulang " << ulang - 1 << " kali." << endl;
break;
}
else {
//...
}
From the istream::operator>> man page:
If extraction fails (e.g. if a letter was entered where a digit is
expected), zero is written to value and failbit is set.
So, your function could test the cin.good() method to see if the >> operation was successful, like this:
cin >> p;
if (cin.good()) {
cout << "The integer you typed was " << p << endl;
} else {
cout << "Hey, that wasn't an integer!" << endl;
}

Invalid operand of types 'double' and 'const char[5]' to binary 'operator<<'

I'm trying to make a C++ Acidity/Base Universal Calculator. Upon trying to finalize my code, I stump upon 5 error(s) below;
main.cpp: In function 'int main()':
main.cpp:62:36: error: invalid operands of types 'double' and 'const char [5]' to binary 'operator<<'
cout << "[H+]=" << 10^(W-X) << "*10^" << W << '\n';
^
main.cpp:63:34: error: invalid operands of types 'int' and 'double' to binary 'operator^'
cout << "[OH-]=" << 1/(10^(W-X)) << "*10^" << (-14)-W << '\n';
^
main.cpp:77:33: error: invalid operands of types 'int' and 'double' to binary 'operator^'
cout << "[H+]=" << 1/(10^(U-V)) << "*10^" << (-14)-U << '\n';
^
main.cpp:78:37: error: invalid operands of types 'double' and 'const char [5]' to binary 'operator<<'
cout << "[OH-]=" << 10^(U-V) << "*10^" << U << '\n';
^
D:\EvaxHybrid\Mywork\Cpp\ChempHpOH\Makefile.win:28: recipe for target 'main.o' failed
mingw32-make.exe: *** [main.o] Error 1
I've tried implementing Solution 1 which isn't inline and would make the code too complex to read , Solution 2 which isn't inline and not the same problem (I didn't use new). If there's no other choice, anyone could comment to me about that and I'll do a function related approach.
Here's the code (main.cpp);
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string>
#include <bits/stdc++.h>
#include <stdlib.h>
#include <conio.h>
#include <cmath>
using namespace std;
int main() {
cout << "Choose Start point..." << '\n';
cout << "1. [H+]\n2. [OH-]\n3. pH\n4. pOH\n";
int choice;
cin >> choice;
system ("cls");
switch(choice)
{
case 1:
cout << "Convert [H+] to Scientific Notation of A*10^B and input A,B\n";
system ("pause");
cout << '\n';
double A,B;
cout << "A:";
cin >> A;
cout << '\n';
cout << "B:";
cin >> B;
cout << '\n';
cout << "[H+]=" << A << "*10^" << B << '\n';
cout << "[OH-]=" << 1/A << "*10^" << (-14)-B << '\n';
cout << "[pH]=" << (-log10(A)-B) << '\n';
cout << "[pOH]=" << 14-(-log10(A)-B) << '\n';
break;
case 2:
cout << "Convert [OH-] to Scientific Notation of Z*10^Y and input Z,Y\n";
system ("pause");
cout << '\n';
double Z,Y;
cout << "Z:";
cin >> Z;
cout << '\n';
cout << "Y:";
cin >> Y;
cout << '\n';
cout << "[H+]=" << 1/Z << "*10^" << (-14)-Y << '\n';
cout << "[OH-]=" << Z << "*10^" << Y << '\n';
cout << "[pH]=" << 14-(-log10(Z)-Y) << '\n';
cout << "[pOH]=" << (-log10(Z)-Y) << '\n';
break;
case 3:
cout << "Input pH as X\n";
system ("pause");
cout << '\n';
double X;
cout << "X:";
cin >> X;
double W;
W = -ceil(X);
cout << '\n';
cout << "[H+]=" << 10^(W-X) << "*10^" << W << '\n';
cout << "[OH-]=" << 1/(10^(W-X)) << "*10^" << (-14)-W << '\n';
cout << "[pH]=" << X << '\n';
cout << "[pOH]=" << 14-X << '\n';
break;
case 4:
cout << "Input pOH as V\n";
system ("pause");
cout << '\n';
double V;
cout << "V:";
cin >> V;
double U;
U = -ceil(V);
cout << '\n';
cout << "[H+]=" << 1/(10^(U-V)) << "*10^" << (-14)-U << '\n';
cout << "[OH-]=" << 10^(U-V) << "*10^" << U << '\n';
cout << "[pH]=" << 14-V << '\n';
cout << "[pOH]=" << V << '\n';
break;
}
}
Operator << has precedence over operator ^.
cout << "[H+]=" << 10^(W-X) << "*10^" << W << '\n';
is read as
(cout << "[H+]=" << 10) ^ ((W-X) << "*10^" << W << '\n');
Put parenthesis:
cout << "[H+]=" << (10^(W-X)) << "*10^" << W << '\n';

Cannot print buffer address

I want to test the following code, however I get a compilation error. The thing that confuse me is that the way and create and print pd1 and pd2 are the same as pd3 and pd4, but the compiler complains about pd3 and pd4 when I print.
const int BUF = 512;
const int N = 5;
char buffer[BUF]; // chunk of memory
int main(){
using namespace std;
double *pd1, *pd2;
int i;
cout << "Calling new and placement new:\n";
pd1 = new double[N]; // use heap
pd2 = new (buffer) double[N]; // use buffer array
for (i = 0; i < N; i++)
pd2[i] = pd1[i] = 1000 + 20.0*i;
cout << "Buffer addresses:\n" << " heap: " << pd1 << " static: " << (void *)buffer << endl;
cout << "Buffer contents:\n";
for(i = 0; i < N; i++) {
cout << pd1[i] << " at " << &pd1[i] << "; ";
cout << pd2[i] << " at " << &pd2[i] << endl;
}
cout << "\nCalling new and placement new a second time:\n";
double *pd3, *pd4;
pd3 = new double[N];
pd4 = new (buffer) double[N];
for(i = 0; i < N; i++)
pd4[i] = pd3[i] = 1000 + 20.0 * i;
cout << "Buffer contents:\n";
for (i = 0; i < N; i++) {
cout << pd3[i] < " at " << &pd3[i] << "; ";
cout << pd4[i] < " at " << &pd4[i] << endl;
}
return 0;
}
Compilation error:
newplace.cpp: In function ‘int main()’:
newplace.cpp:33:36: error: invalid operands of types ‘const char [5]’ and ‘double*’ to binary ‘operator<<’
cout << pd3[i] < " at " << &pd3[i] << "; ";
^
newplace.cpp:34:36: error: invalid operands of types ‘const char [5]’ and ‘double*’ to binary ‘operator<<’
cout << pd4[i] < " at " << &pd4[i] << endl;
You missing one < symbol here
cout << pd3[i] < " at " << &pd3[i] << "; ";
cout << pd4[i] < " at " << &pd4[i] << endl;
Try
cout << pd3[i] << " at " << &pd3[i] << "; ";
cout << pd4[i] << " at " << &pd4[i] << endl;
You only put one < in the stream where you are trying to print out the buffer contents.
cout << pd3[i] < " at " << &pd3[i] << "; "; // there is only one <
cout << pd4[i] < " at " << &pd4[i] << endl; // ^
Make sure you have two <'s in the stream insertion operator.
cout << pd3[i] << " at " << &pd3[i] << "; ";
cout << pd4[i] << " at " << &pd4[i] << endl;

Calculator in C++ Help. Can't Return Running Total [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have to make a Calculator using a constructor and destructor, that adds, subtracts, multiplies and divides, and returns the total every time. For some reason, when I call the line "Calculator.add(num);" or any of the "Calculator." portions return me an error saying that it "expected an identifier". Am I missing something simple?
Thanks.
Here is my main.cpp file.
#include <iostream>
#include "Calculator.h"
#include <cstdlib>
using namespace std;
double total;
int main(){
while (true){
cout << "*** Calculator *** " << endl;
cout << "A: Add a value " << endl;
cout << "S: Subtract a value " << endl;
cout << "M: Multiply by a value " << endl;
cout << "D: Divide by a value " << endl;
cout << "T: Get the total " << endl;
cout << "Q: Quit " << endl;
cout << endl;
char input;
cin >> input;
if (input == 'A'){
cout << "Current Total: " << total << endl;
cout << "Selection: A";
cout << endl;
cout << "*** Add selected *** " << endl;
cout << "Value:";
double num;
cin >> num;
cout << endl;
double turnTotal = total;
Calculator.add(num);
cout << turnTotal << "+" << num << " = " << total;
}
if (input == 'S'){
cout << "Current Total: " << total << endl;
cout << "Selection: S";
cout << endl;
cout << "*** Subtract selected *** " << endl;
cout << "Value: ";
double num2;
cin >> num2;
cout << endl;
double turnTotal2 = total;
Calculator.subtract(num2);
cout << turnTotal2 << "-" << num2 << "=" << total;
}
if (input == 'M'){
cout << "Current Total: " << total << endl;
cout << "Selection: M";
cout << endl;
cout << "*** Multiply selected *** " << endl;
cout << "Value: ";
double num3;
cin >> num3;
cout << endl;
double turnTotal3 = total;
Calculator.multiply(num3);
cout << turnTotal3 << "*" << num3 << "=" << total;
}
if (input == 'D'){
cout << "Current Total: " << total << endl;
cout << "Selection: D";
cout << endl;
cout << "*** Divide selected *** " << endl;
cout << "Value: ";
double num4;
cin >> num4;
cout << endl;
double turnTotal4 = total;
Calculator.divide(num4);
cout << turnTotal4 << "/" << num4 << "=" << total;
}
if (input == 'T'){
cout << "Current Total: " << total << endl;
cout << "Selection: T";
cout << endl;
cout << "*** Total selected *** " << endl;
cout << "Value: ";
double num5;
cin >> num5;
cout << endl;
double turnTotal5 = total;
Calculator.getTotal(num5);
cout << turnTotal5 << "-" << num5 << "=" << total;
}
if (input == 'Q'){
cout << "Thank you for using the calculator! Bye bye! Have a great day!" << endl;
}
}
}
And here is the .cpp file
#include <cstdlib>
#include <iostream>
#include "Calculator.h"
using namespace std;
Calculator::Calculator(double x){
double total = x;
return;
}
double Calculator::getTotal(){
return total;
}
void Calculator::add(double x){
total += x;
}
void Calculator::subtract(double x){
total -= x;
}
void Calculator::multiply(double x){
total *= x;
}
void Calculator::divide(double x){
total /= x;
}
And here's the class .h file.
#include <cstdlib>
#include <iostream>
using namespace std;
//class specification
class Calculator {
public:
//constructor
Calculator(){double total = 0;}
Calculator(double total);
//member functions
void add(double x);
void subtract(double x);
void multiply(double x);
void divide(double x);
double getTotal();
//destructor
~Calculator();
private:
//data
double total = 0;
};
You doesn't seem to initialize your Calculator first. You could add the initialization for example on the start of main function as follows
double total;
Calculator calc;
int main(){
while (true){
And then use it like
calc.add(num);