getting dummy value in C++ code rather than expected value - c++

I am having issue in understanding that why my code is providing me some dummy value.
Can someone help me out that where I am at fault and what is the reason ?
#include <stdio.h>
#include <iostream>
class mypair
{
public:
int a,b;
public:
int print (int first , int second)
{
a = first;
b = second;
std::cout<<a <<" hello "<<b;
}
int getmax();
};
int mypair ::getmax()
{
int res;
res = (a>b)?a:b;
std::cout<<res;
return res;
}
int main ()
{
mypair abc;
std::cout<<abc.print(5,6);
std::cout<<abc.getmax();
}

print() doesn't return any value but it is expected to return an int. This is UB, and your dummy values are caused by this.
In addition, in both print() and getmax() you send output to cout. In the case of getmax(), this output will immediately predede the output of the return value, causing the same number to be displayed twice without any space or separator.

Related

how to add an element to the string position of a vector

I want the add function in the Carnet class to add a number to a position (position to be a string) and when I display myclass << ["string"] to display the number
the problem is that when I run the instructions in the main it shows me wrong(7,7,7), instead of showing me 7,9,10
I think the problem is saving in vector but I do not know how to fix it, I tried this:
this->insert(this->begin() + atoi(a.c_str()), b);
#include <iostream>
#include <vector>
using namespace std;
template <typename ElementT>
class Carnet : public vector<ElementT> {
public:
Carnet() : vector<ElementT>() {
}
int operator[] (string materie) {
return this->at(atoi(materie.c_str()));
}
Carnet add(string a, int b) {
this->insert(this->begin() + atoi(a.c_str()), b);
return *this;
}
Carnet removeLast() {
this->pop_back();
return *this;
}
};
int main()
{
Carnet<int> cat;
cat.add("SDA", 9);
cat.add("OOP",7).add("FP", 10);
cout<<cat["OOP"];
cout<<cat["SDA"];
cout<<cat["FP"];
cat.removeLast().removeLast();
return 0;
}
The problem is here:
Carnet add(string a, int b) {
this->insert(this->begin() + atoi(a.c_str()), b);
return *this;
When you returning by value, you are making a copy, which means here
cat.add("OOP",7).add("FP", 10);
the second add will operate on a new object instead of on cat.
You should use a reference instead:
Carnet& add(string a, int b) {
Same problem with removeLast.
Edit: Also, deriving from vector is generally not advisable. You should consider using composition instead.
Edit 2: There is a more fundamental problem. atoi should only ever return 0 here, because you never present it with any number strings.
It is not entirely clear what you are intending to do here. But maybe a vector is the wrong container? It seems you want to associate a number with a string. A std::map<std::string, int> could do the job.

How to freeze a variable since it first assigned?

Please assume the version of gcc 7.2.1 in this question
I would like to declare a global variable which behave like a const however, the value to initialize it cannot not be detected before the program being executed. In other words, the target variable would be re-assigned since the first time it is assigned.
An ugly approach of this concept as follow:
#include<iostream>
int numberOfPeople; //Do not re-assign it after it first assign
int main(){
std::cin >> numberOfPeople; // Do not re-assign numberOfPeople since then !!!
// Following of codes omitted.
}
As you could see, this is a very ugly approach and cannot be checked by compiler. I wonder whether there is a kind of notation in c++ that can freeze the variable since it first assigned.
So I can write code like this:
#include<iostream>
magic_notation int numberOfPeople;
int main(){
std::cin >> numberOfPeople; // Allowed as it's first assign.
// Median codes omitted.
numberOfPeople = 60. //Disallowed and will get an error message from compiler!
// Following codes omitted.
}
Is there any kind of notation as can use like the magic_notation in the code above in c++?
The best approach is to make a class with a public const member variable which gets initialized in the constructor:
struct InitInfo {
const int numberOfPeople;
InitInfo() numberOfPeople(getNumberOfPeople()) {
}
private:
static int getNumberOfPeople() {
int res;
cin >> res;
return res;
}
};
InitInfo initInfo;
Now you can use the member variable as follows:
int main() {
cout << initInfo.numberOfPeople << endl;
}
You can use the same approach for initializing a global variable, too.
static int getNumberOfPeople() {
int res;
cin >> res;
return res;
}
const int numberOfPeople = getNumberOfPeople();
int main() {
cout << numberOfPeople << endl;
numberOfPeople += 10; // <<== This triggers an error
}
One approach you can use is to wrap the variable as a static variable in a function. Use the function instead of the variable in rest of your code.
#include <iostream>
int readFromStdin()
{
int n;
cin >> n;
return n;
}
// Wrap it arund in a function.
// int numberOfPeople; //Do not re-assign it after it first assign
int getNumberOfPeople()
{
// Initialize by reading from stdin.
static int numberOfPeople = readFromStdin();
returnn numberOfPeople;
}
int main(){
// Use the function instead of the variable.
getNumberOfPeople();
}
In case you have different ways to initialize the variable, you could come up with something like this:
struct {
int value() const { return _val; }
void init(int val) {
if(!_set) _val = val;
}
private:
int _val;
bool _set = false;
} numberOfPeople;
Now, everybody who uses the variable should call init before using it to make sure it is initialized.

How to pass an input from c++ function to the main function

i want to take an input from c++ function and return it to the main function
, i've already tried to do it but the function returns zero , any idea ?
#include<iostream>
using namespace std;
int input( int x);
int main()
{
int number;
input(number);
cout<<number;
}
int input (int x)
{
cin>>x;
return x;
}
you need to pass by reference
void input (int & x)
{
cin>>x;
}
or use the return value
int main()
{
int number;
number = input();
cout<<number;
}
int input ()
{
cin>>x;
return x;
}
You can change your function to make it take x by reference:
void input (int& x)
{
cin>>x;
}
This way, you don't even need to return x, because your function will update its value as it is passed by reference.
So, let's get it from the begining :
It any function, all its variables are temporary and only accessible in this function's scope unless you use a pointer or a reference(c++ only)
So what happen when you call your function is that a copy of number's is created into x
Also, the return statement of a function is used to... return values! Yeah, weird uh?
So actually you don't even need to send any parameter to your function and just take its result :
#include<iostream>
using namespace std;
int input();
int main()
{
int number = input(); // Takes what the return statement gives
cout<<number;
}
int input ()
{
int x;
cin>>x;
return x;
}
Here's another way by using c++'s references :
#include<iostream>
using namespace std;
void input( int& x);
int main()
{
int number;
input(number);
cout<<number;
}
int input (int& x)//Takes number's address
{
cin>>x;
}

How to create a Function that return any array of structs

I know there has to be a better and easier way to do what I am trying to do so I'm sorry for my lack of knowledge of programming. My program crashes when I call the function printStructValue. I have left comments to explain my thought process.
#include <iostream>
#include <vector>
using namespace std;
struct selection //vector array to tell me what is selected. ex:'w',5 is wall 5
{
char c;
int id;
}; vector<selection> Sel(20,selection());
struct walls //struct to hold wall data
{
int id;
int x,y,z;
int spriteState;
}; walls W[10];
struct floors //struct to hold floor data
{
int id;
int x,y,z;
}; floors F[10];
template <typename T,typename U>
T returnAnyArray(int st, T t,U u) //function that returns any type passed
{
if(st==1){t;} //if st==1, then return the first, walls W
if(st==2){u;} //if st==2, then return the second, floors F
}
template <typename T>
void printStructValue(T t, int d) //print any struct value
{
cout<<"passed:"<<t[d].x<<endl;
}
int main()
{
W[7].x=204; //init value
F[7].x= 73; //init value
//what I would like to happen is...
printStructValue( (returnAnyArray(1,W,F)),7); //W is returned and passed so W[7].x gets printed.
printStructValue( (returnAnyArray(2,W,F)),7); //F is returned and passed so F[7].x gets printed.
system("pause");
}
Your returnAnyArray function has to return something, but the types also have to match. Try this
template<typename T, typename U>
auto returnAnyArray(int st, T t, U u) -> decltype(st == 1 ? t : u)
{
return st == 1 ? t : u;
}
Your template function, returnAnyArray, doesn't actually return anything. Hence, printStructValue is being passed a garbage pointer. I'm surprised the compiler didn't catch this and print a warning or error. Perhaps because it's a template.
Do it the C++ way:
struct structuralMember {
virtual ~structualMember() { }
virtual void printme(std::ostream& out) = 0;
};
struct walls : public structualMember {
int x;
void printme(std::ostream& out) { out << x; }
};
struct floors : public structuralMember {
int x;
void printme(std::ostream& out) { out << x; }
};
Of course, that's not terribly sophisticated either, but it's a start.
Something working, but probably not what you are expecting ?
#include <iostream>
#include <vector>
using namespace std;
struct walls //struct to hold wall data
{
int id;
int x,y,z;
int spriteState;
};
walls W[10];
struct floors //struct to hold floor data
{
int id;
int x,y,z;
};
floors F[10];
void printStructValue(walls * t, int d) //print any struct value
{
cout<<"passed:" << t[d].x<<endl;
}
void printStructValue(floors * t, int d) //print any struct value
{
cout<<"passed:"<< t[d].x<<endl;
}
int main()
{
W[7].x=204; //init value
F[7].x= 73; //init value
//what I would like to happen is...
printStructValue( W,7); //W is returned and passed so W[7].x gets printed.
printStructValue( F,7); //F is returned and passed so F[7].x gets printed.
}

possible scope issue c++

#include<iostream>
#include<vector>
using namespace std;
class t{
public:
t();
void updateSize();
int getSize();
void insert();
int get(int a);
private:
int size;
vector<int> v;
};
t::t(){
size =0;
}
void t::updateSize(){
size++;
}
int t::getSize(){
return size;
}
int t::get(int a){
return v[a];
}
void t::insert(){
v.push_back(size);
++size;
}
int main(){
t xa;
xa.insert();
xa.insert();
xa.insert();
xa.insert();
cout<<xa.get(3);//expect to output 3 but instead outputs 0
return 0;
}
this code is supposed to increment the size every time I call insert, and put an integer of with the value of that size in a vector at the same index of that size. But for some reason it does not put the updated size into my vector.
You're inserting 3 elements but you're reading the 4th (since the indexing is 0 based).
The program you posted will print "3". Proof read your code.