How is "a" used in my program? - c++

new to learning c++ and I was wanting to understand the program ive practiced. I have a section of code I want to understand but im kind of lost.
#include "stdafx.h";
#include <iostream>;
// getValueFromUser will read a value in from the user, and return it to the caller
int getValueFromUser()
{
std::cout << "Enter an integer: ";
int a;
std::cin >> a;
return a;
}
int main()
{
int x = getValueFromUser(); // first call to getValueFromUser
int y = getValueFromUser(); // second vall to getValueFromUser
std::cout << x << " + " << y << " = " << x + y << std::endl;
return 0;
}
Im just wanting to know how " int a " comes into play here. If someone could help it would be appreciated.

You declare an uninitialized variable of type int with identifier a:
int a;
The user provides a value to a.
std::cin >> a;
A copy is returned from the function:
return a;
Calls to the getValueFromUser() will create a temporary a,
assign it to user input, and return it each time.

In c++ you have to declare variable (providing the type and name) before it's first use.
std::cin has to put it's output somewhere and that's why you need this additional variable.

Related

C++ beginners question how to access variables

So basicly my questions include when to use parameters and when I dont need them.
I try to learn from examples and this one I can't fully understand:
I will add the questions to the part where I dont understand something after "//" on the right side of the line.
Maybe someone can give me a good explanation, what I need to do in which scenario or good sources where I can look this up on my own.
class Student with public attributes:
#include <iostream>
class Student
{
public:
int stud_ID;
char stud_Name[22];
int stud_Age;
};
function which I want included in int main():
void studentinformation(Student); //#1Why do I must include (Student) in this fuction? ->
// If I dont add this parameter in here, there is no connection ->
//to the function studentinformation(s) in int main.
//Why exactly is that the case ?
main function to get information:
int main(){
Student s;
std::cout<<"Type in ID:";
std::cin >> s.stud_ID;
std::cout<<"Type in youre Name:";
std::cin.ignore(); //
std::cin.getline(s.stud_Name, 22); //#2 Why is std::getline(std::cin, s.stud_Name) not working ?->
std::cout<<"Type in age:"; //#3 Or is there a better alternative ?
std::cin >> s.stud_Age;
studentinformation(s); //#4 Why do I must include the parameter s ?
return 0;
}
function to print information:
void studentinformation(Student s) // #5 Why do I must include the Parameters ?
{ std::cout<<" Student information:"<< std::endl;
std::cout<<" Student ID:" << s.stud_ID << std::endl;
std::cout<<" Name:" << s.stud_Name<< std::endl;
std::cout<<" Age:" << s.stud_Age<< std::endl;
}
studentinformation() is a free function with no connection to any instance of Student which is why you need to supply one as an argument.
std::getline() works on std::strings ...
... and you'd be doing yourself a favour if you changed char stud_Name[22]; to std::string stud_Name;.
For the same reason as in 1.
For the same reason as in 1. 1, 4 and 5 are questioning the same thing.
An alternative would be to make studentinformation() a Student member function instead. You could then call s.studentinformation(); to print info about that particular student.
class Student {
public:
int stud_ID;
std::string stud_Name; // suggested change
int stud_Age;
void studentinformation() const { // const since the object (this) won't be altered
std::cout << " Student information:" << '\n';
std::cout << " Student ID:" << stud_ID << '\n';
std::cout << " Name:" << stud_Name << '\n';
std::cout << " Age:" << stud_Age << '\n';
}
};

Null output in using class methods

In following code I get no output from directly calling sumit() function, but when I call it through the other function displayIt() (which calls sumit() ), it displays the output. How can I fix it? And please also explain what is happening?
#include<iostream>
#include<string>
using namespace std;
template <typename C>
class ABC
{
private:
C num1, num2;
public:
ABC(C a, C b)
{
num1 = a;
num2 = b;
}
void displayIt()
{
cout << "A+B:" << sumit() << endl;
}
C sumit() { return num1 + num2; }
};
int main()
{
ABC<int> o1(2, 3);
ABC<string> o2("ABC", "XYZ");
//It doesn't display aything...
cout << "Call-1: " << endl;
o1.sumit();
o2.sumit();
//It displays the output...
cout << "Call-2: " << endl;
o1.displayIt();
o2.displayIt();
system("pause");
}
Of course you get no output , because this method isn't trying to print anything . It simply returns a number.
Either do this in main :
cout << o1.sumit() << endl;
cout << o2.sumit() << endl;
Which will directly print the value returned from this method.
Or add the same logic of displayIt to sumit .
BTW - This question is irrelevant to C++ Template . The same behaviour would have happened in a regular class .

structure and functions in C++

Can someone explain why this code gives the output 10? When I try to analyse it my logic gives as result 11.
#include <iostream>
using namespace std;
class A {
public:
A() { a.a = a.b = 1; }
struct { int a,b; } a;
int b(void);
};
int A::b(void) {
int x=a.a;
a.a=a.b;
a.b=x;
return x;
};
int main(void) {
A a;
a.a.a = 0;
a.b();
cout << a.b() << a.a.b << endl;
return 0;
}
In the cout line, a.b() could either be called before or after a.a.b is evaluated. Beginners sometimes assume left-to-right evaluation in this sort of code but actually that is not a rule of C++.
Those two different possibilities would explain your 10 and 11. To avoid ambiguity you could write:
cout << a.b();
cout << a.a.b << endl;
(assuming that order was your intent).
Note: C++17 may change this and define left-right evaluation order for this code.
Other than using a debugger, you can also use cout statements to help keep track of when things are called.
To kind of help myself out tracing your program I fixed a bit of the indentation and added comments as to when things are happening:
#include <iostream>
using namespace std;
class A {
public:
A() {
a.a = a.b = 1;
}
struct {
int a,b;
} a;
int b(void);
};
int A::b(void) {
cout << "Within A::b()" << endl;
// swap a.a, a.b
int x=a.a;
a.a=a.b;
a.b=x;
cout << "a.a.a = " << a.a << " a.a.b: " << a.b << endl;
return x;
};
int main(void) {
// sets a.a.a = 1, a.a.b = 1
A a;
// sets a.a.a = 0, a.a.b = 1
a.a.a = 0;
// a.a.a = 1, a.a.b = 0
a.b();
// check output here
cout << a.b() << a.a.b << endl;
return 0;
}
The above program results with the following output on http://cpp.sh/ :
Within A::b()
a.a.a = 1 a.a.b: 0
Within A::b()
a.a.a = 0 a.a.b: 1
10
In all, it depends on whether or not a.b() or a.a.b is resolved first when you call cout. In this case, operator precedence is undefined due to how cout works. This stackoverflow post has some good info on this.

C++ Can't figure out output for a class that holds player information. It outputs garbage

I've been pulling my hair out trying to figure out this program. The class has to hold 3 player's info and output their info. My output function is not outputting from my set/get functions. Also, if I output the array indexes the program crashes (that's the array indexes are commented out in the Output function).
edit: I'll just show one profile to keep the code smaller
Any help is appreciated.
#include <cstdlib>
#include <iostream>
using namespace std;
class PlayerProfile
{
public:
void output();
void setName1(string newName1); //player's name
void setPass1(string newPass1); //player's password
void setExp1(int newExp1); //player's experience
void setInv1(string newInv1[]); //player's inventory
void setPos1(int newX1, int newY1); //player's position
string getName1();
string getPass1();
int getExp1();
string getInv1();
int getPos1();
private:
string name1;
string pass1;
int exp1;
string inv1[];
int x1;
int y1;
};
int main(int argc, char *argv[])
{
PlayerProfile player;
cout << "This program generates three player objects and displays them." << endl;
cout << endl;
player.output();
system("PAUSE");
return EXIT_SUCCESS;
}
void PlayerProfile::setName1(string newName1)
{
newName1 = "Nematocyst";
name1 = newName1;
}
void PlayerProfile::setPass1(string newPass1)
{
newPass1 = "obfuscator";
pass1 = newPass1;
}
void PlayerProfile::setExp1(int newExp1)
{
newExp1 = 1098;
exp1 = newExp1;
}
void PlayerProfile::setInv1(string newInv1[])
{
newInv1[0] = "sword";
newInv1[1] = "shield";
newInv1[2] = "food";
newInv1[3] = "potion";
inv1[0] = newInv1[0];
inv1[1] = newInv1[1];
inv1[2] = newInv1[2];
inv1[3] = newInv1[3];
}
void PlayerProfile::setPos1(int newX1, int newY1)
{
newX1 = 55689;
x1 = newX1;
newY1 = 76453;
y1 = newY1;
}
string PlayerProfile::getName1()
{
return name1;
}
string PlayerProfile::getPass1()
{
return pass1;
}
int PlayerProfile::getExp1()
{
return exp1;
}
string PlayerProfile::getInv1()
{
return inv1[0], inv1[1], inv1[2], inv1[3];
}
int PlayerProfile::getPos1()
{
return x1, y1;
}
void PlayerProfile::output()
{
cout << "Player Info - " << endl;
cout << "Name: " << name1 << endl;
cout << "Password: " << pass1 << endl;
cout << "Experience: " << exp1 << endl;
cout << "Position: " << x1 << ", " << y1 << endl;
cout << "Inventory: " << endl;
/*cout << inv1[0] << endl;
cout << inv1[1] << endl;
cout << inv1[2] << endl;
cout << inv1[3] << endl; */
}
This is the output that I am getting:
This program generates three player objects and displays them.
Player Info -
Name:
Password:
Experience: -2
Position: 3353072, 1970319841
Inventory:
Press any key to continue . . .
I'm sorry if I sound like an idiot, this is the first time I have programmed with classes and I am very confused.
First:
You do not have a constructor declared or defined in your class so when you compile, the compiler provides you with a default constructor.
The line
PlayerProfile player;
calls the default constructor provided by the compiler. This default constructor only allocates memory for your class member variables, but does not set their values. This is why name1, pass1, exp1, x1, y1 are not outputting what you expect.
Second:
C++ will not call get or set functions for you, and I think you are misunderstanding how c++ functions work.
this
void PlayerProfile::setName1(string newName1)
{
name1 = newName1;
}
is a function definition. You do not need to assign newName1 inside the function. It's value is passed to the function when a line like
setName1("Nematocyst");
is executed.
If you write a constructor, you can use it to call your set functions, and pass them the values you want to set member variables to.
If you do not want to write a constructor, you can call class functions/methods from main with:
player.setName1("Nematocyst");
Third:
Your program crashes because you are not using arrays properly. Here is a tutorial on how to declare an array and access it's contents.
Generally, I think you are trying to run before you know how to walk. Try not to get frustrated. Learn how arrays work, how functions work, and then how classes work. I hope this is not your homework assignment!

Reading from file and storing attributes gives wrong output

I'm trying to read a text file that consists of the following three attributes;
RouterID, X-coordinate, Y-coordinate.
A brief snippet of the txt file is shown below;
100 0 0
1 20.56 310.47
2 46.34 219.22
3 240.40 59.52
4 372.76 88.95
Now, what I'm trying to achieve is to make a node for every RouterID and store its corresponding x and y co-ordinates. For this purpose, I have created the following class;
class Node {
public:
float routerID;
float x;
float y;
void set_rid (float routerID) {
routerID = routerID;
}
void set_x_y (float x, float y) {
x = x;
y = y;
}
};
And I have the following which performs the job of creating a new node for every routerID;
const std::string fileName = "sampleInput.txt";
std::list<Node> nodeList;
int main (void) {
std::ifstream infile(fileName);
float a(0);
float b(0), c(0);
//This reads the file and makes new nodes associated with every input
while (infile >> a >> b >> c) {
Node newNode;
newNode.set_rid (a);
newNode.set_x_y (b, c);
std::cout << "newNode " << "rid = " << newNode.routerID << " x = " << newNode.x << " y = " << newNode.y << std::endl;
nodeList.push_back(newNode);
}
I'm performing the following line inside my while loop just to check whether or not the values being assigned are correct or not.
std::cout << "newNode " << "rid = " << newNode.routerID << " x = " << newNode.x << " y = " << newNode.y << std::endl;
When I compile and run the code, I get the following as my output for all of them;
newNode rid = -1.07374e+008 x = -1.07374e+008 y = -1.07374e+008
I've just started learning C++ last week and this is my first "big" program that I am trying to code. Could anyone please point me in the right direction?
void set_rid (float routerID) {
routerID = routerID;
}
This doesn't do what you seem to think it does. It assigns the parameter to itself; the value of this->routerID remains unchanged. Same with set_x_y. Just give the method parameters some names that are different from those of data members.
Another to distinguish class variables from input parameter is by using the keyword this. thus you can make a reference to class variables by calling this.routerID, this.x and this.y