This question already has answers here:
How to set cin to a member function of a class in C++?
(3 answers)
Closed 2 years ago.
This is my first time using classes and I'm writing a simple program that will take a certain roman numeral and print out the numerical equivalent. However, I'm struggling to code my user input, my cin >> romanObject.getRomanNumeral(); isn't working. I get error E0349 saying no operator ">>" matches these operands. However, when I used just a simple char variable declared in my main function instead it worked fine. Why doesn't my variable in my class work?
#include <iostream>
#include <string>
using namespace std;
class romanType {
public:
void setRomanNumeral(string x) {
romanNumeral = x;
}
string getRomanNumeral() {
return romanNumeral;
}
private:
string romanNumeral;
};
void store();
int main()
{
store();
return 0;
}
void store() // Takes user input.
{
romanType romanObject;
romanObject.setRomanNumeral("Blank");
cout << "Enter one of the following roman numerals" << endl;
cout << "I, V, X, L, C, D, M." << endl;
cin >> romanObject.getRomanNumeral();
}
Why doesn't my variable in my class work?
It works just fine, except that you're not returning it. When you are returning something by value, you are essentially making a temporary copy of the variable. Of course, you can return it by reference:
string &getRomanNumeral() {
return romanNumeral;
}
However, that doesn't really make much sense, since you no longer need setRomanNumberal(), you can simply use getRomanNumberal():
romanObject.getRomanNumeral()="hello world";
The detail that you missed that setting the value of your class member is a part of initializing it by reading its value from std::cin. After you read the string, what do you need to do? You need to set it, so why do you want to use something called getRomanNumeral()? That doesn't make much sense, doesn't that?
So, really, your original approach was the correct one, something along the lines of:
string s;
cin >> s;
romanObject.setRomanNumeral(s);
You're getting the variable, from cin, and you're setting it in your object; you're not getting the existing value of this variable in your object, at any point.
Related
Ok, i have a program I'm trying to make and the basic thing is to keep me from rewriting the same long 4 lines of code over and over throughout the project, I'm wanting to see if i can get it to take a string from cin and make the whole string lowercase (I'm aware of the transform method, but this is so i don't have to write really length if statements) and return that string to be used as a variable in other parts of the program or other functions.
I don't know if I'd just have to make the function's return the variable itself in the main block or what. I'm pretty new to c++ and coding in general, if its possible id like to include spaces, in the string. Again I'm not too experienced in c++ yet so id like to know if its even possible and if so the best way to do it.
here is what i have so far
int loAns() {
string lAnswer; //Makes the lAnswer, a string used for a long answer that a char wouldn't do properly
cin >> lAnswer; //User enters it
// using transform() function and ::tolower
transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower); //The transform and ::tolower to make it uniform
cout << lAnswer << endl; //Outputs the lAnswer to console
return 0; //This is where I'm assuming the variable gets put to be used in the rest of the program
}
Your interpretation is correct. Essentially, a function is declared as such:
type name ( parameter1, parameter2, ...)
{
//statements
return <var>;
}
The type is for returning variables back to other programs. In this case, you want to return a std::string, so you function could be like this:
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string loAns()
{
string lAnswer;
cin >> lAnswer;
transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower);
return lAnswer;
}
int main()
{
string s = loAns();
cout << s;
}
Result :
xYZabC123
xyzabc123
If you wanted spaces in your string, it's possible to use getline():
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string loAns()
{
string lAnswer;
getline(cin, lAnswer);
transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower);
return lAnswer;
}
int main()
{
string s = loAns();
cout << s;
}
Result :
ABc XYZ 123&A
abc xyz 123&a
More info:
Functions : https://en.cppreference.com/w/cpp/language/functions
return : https://en.cppreference.com/w/cpp/language/return
getline() : https://en.cppreference.com/w/cpp/string/basic_string/getline
Ran on Code::Blocks 20.03, Windows 10 64-bit
Also, as #David C. Rankin mentioned below, using namespace std; is not considered a good practice.
I have started learning C++ recently, doing some simple class/friend function practice, What i was trying to do is, get 2 numbers from user for 2 object of a class by using friend functions only then again using friend function only, multiply those 2 numbers and show on screen. Let's say i typed 2, 3, 4, 5 in order. Expected outputs are 6 and 20, but i can only see 0 and 0 on screen.
#include<iostream>
using namespace std;
class iluvcpp {
int no_1, no_2;
public:
iluvcpp(){}
~iluvcpp(){}
friend void inputno(iluvcpp obj);
friend int multiply(iluvcpp obj);
}multi_1, multi_2;
void inputno(iluvcpp obj) {
cout <<"Enter no 1: ";
cin >> obj.no_1;
cout <<"Enter no 2: ";
cin >> obj.no_2;
}
int multiply(iluvcpp obj) {
return ((obj.no_2)*(obj.no_1));
}
int main() {
inputno(multi_1);
inputno(multi_2);
cout << multiply(multi_1) <<" "<< multiply(multi_2);
cout << endl;
system("pause");
return 0;
}
You pass your objects by value, meaning when you call inputno you're working on a copy. Try changing the function signature to:
void inputno(iluvcpp& obj) {
...
}
Here's an explanation with examples about passing parameters by value vs by reference.
2 suggestions:
A variable/method of a class is private by default. Either make your variables no_1 and no_2 public as well, or write a setter, if you're familiar with it. To have them public by default, use struct, as opposed to class.
As others already have pointed out, you're not modifying multi_1 and multi_2 directly. Either have them passed in by reference (The answer of orip mentions exactly that), or make them return this iluvcpp obj Object and call them like:
multi_1 = inputno(multi_1);
void inputno(iluvcpp obj) has one parameter named obj and no return value. That's the wrong way around here, inputno doesn't need anything from main but it should return something:
iluvcpp inputno(void) { ... or (equivalent) iluvcpp inputno() { ....
You'll need a return something; statement at the end, so C++ knows what value to return from inputno.
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 5 years ago.
Improve this question
sorry if this is obvious, I am new to classes.
I want the code to read the first value of a file from a class constructor (a getter), and right now the constructor returns a random number instead of the first number of the file, so it's clearly not reading the file for some reason. Thank you for your help, the code is in the following link.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
class bankAccount
{
public:
int getAcctNum();
bankAccount(string n);
bankAccount();
private:
ifstream sourceFile;
char tempWord;
int accountNumber;
double initialBalance;
double interestRate;
double serviceCharge;
double depositAmt;
double withdrawAmt;
double totalDeposits;
double totalWithdraws;
double tempAmt;
};
int main()
{
string fileName;
cout << "Enter the name of the data file: ";
cin >> fileName;
cout << endl;
bankAccount object(fileName);
cout << "Account number: " << object.getAcctNum() << endl;
return 0;
}
bankAccount::bankAccount(string n)
{
ifstream sourceFile(n.c_str());
}
bankAccount::getAcctNum()
{
sourceFile >> tempWord;
sourceFile >> accountNumber;
return accountNumber;
}
The value in the file that it should read is:
# 123456
Your problem has to do with scope. For a quick TL;DR how do I fix it, just scroll all the way to the bottom.
An easy way to think of scope is by thinking: where is my variable defined. A variable defined outside of main is said to have global scope, as it's a global variable. That means that no matter where you reference it (after it's definition) it will be defined (not necessary initialized, however). If a variable is defined within a function, it's scope is limited to that function. So it will be defined in that function only, not in other functions. If you define a variable within a for loop, or an if statement, or anywhere were you open a new scope using { }, that variable is scope-limited, ie it is only defined in that scope, and will stop being defined after the closing brace is read. Here is an example:
#include <iostream>
// rest of includes and usings and function prototypes, etc
const string AUTHOR_NAME = "ME"; // this is now defined everywhere in the program.
int main() {
bool program_busy = true; // this is only defined in main()
}
bool return_program_busy() {
cout << AUTHOR_NAME << endl; // this works as AUTHOR_NAME is defined
return program_busy; // this won't work, as program_busy is not defined in this scope.
}
void better_example(bool program_busy) {
int version = 0.1;
for(int i = 0; i < 10; i++) {
do_something(version, i); // this works as both are defined.
}
// i is no longer defined as we exited it's scope!!
if(program_busy) { // this opens a new scope.
int version = 0.2;
do_something(version, 0); // wait, is version 0.1 or 0.2???
}
}
As you can undoubtedly see in the last line, there are two versions (with different scopes) that are defined. So which one does it use? The one with the smaller scope, or the more local one. version 0.2 is only defined within the if(program_busy) scope, so it's smaller than the entire function scope, so it is used. Can you spot the error in your own code now?
ifstream sourceFile has two scopes: a global-class one, i.e. it is defined for the entire class, and a local scope for the constructor function you have.
ifstream sourceFile(n.c_str()); will create a new variable with a limited scope and initalize it, leaving the sourceFile with a more global scope uninitialized. The way to fix it is simply not redefine the sourceFile variable.
TL;DR: change ifstream sourceFile(n.c_str()); to sourceFile.open(n.c_str());
My plan was to make a simple addition calculator, and move on from there.
Remember, this is my first day coding.
#include <iostream>
#include <string>
using namespace std;
int a;
int b;
int sum;
string ans;
class CalcClass{
public:
int add (int a, int b) {
cout << "Pick the numbers you want to add" << endl;
cin >> a >> b;
sum = a + b;
return sum;
}
};
Added string ans; (at the top). Now I'm getting an "error: no matching function for call to 'CalcClass::add()'"
Why would it be saying this if I already created calcObject and used calcObject.add(); to call the function?
void pickFunction(){
cout << "What Function do you want to do? \n Add, Subtract, multiply, or divide? ";
cin >> ans;
if (ans == "add"){
CalcClass calcObject;
calcObject.add();
}
int main(){
pickFunction();
cout << "Your answer is : " << sum << endl;
return 0;
}
ans needs a type (probably string), add needs quotes ("add"), CalcClass.calcObject; needs to be CalcClass calcObject;.
'dot' syntax (x.y) is used for accessing data or functions that are stored inside of an object, not a class (e.g. calcObject.add(); rather than CalcClass.add();).
Also, as Mahesh says, pickFunction(); needs to be in main. This should look as follows:
void pickFunction(){
//code
}
int main() {
pickFunction();
//...
}
CalcClass.calcObject;
is not the way to create an object. . operator should be used to access object's members/methods. So, create an object like -
CalcClass calcObject;
Also forward declaration of a class isn't useful if object instantiation takes place before compiler can see the definition. So, make sure compiler sees CalcClass before the pickFunction(). With that said, you have to call the pickFunction from main for your program to do anything useful.
Pick a book from The Definitive C++ Book Guide and start reading.
Just beginning to learn about structs, I thought I understood how they work, using the dot operator to access a member of an object, but i clearly don't as the readEmployeeRecord function below doesn't work at all. How should i be doing this? (the code is short and self explantory)
Many thanks for taking the time to further explain structs to me! Naturally I tried google first but i couldn't find an example that inputted data quite the way i wanted and wasn't sure how i should be going about it.
#include <iostream>
#include <iomanip>
using namespace std;
//Employee type
struct Employee{
float wage;
char status;
char dept[4]; //for 3letter department, last position is \0 correct?
};
//function definitions
void readEmpoyeeRecord(Employee staff);
void printEmployeeRecord(Employee staff);
int main(){
Employee employeeA;
readEmpoyeeRecord(employeeA);
printEmployeeRecord(employeeA);
return 0;
}
void readEmpoyeeRecord(Employee employee){
cout << "Enter empolyees wage: ";
cin >> employee.wage;
cout << "Enter empolyees status (H or S): ";
cin >> employee.status;
cout << "Enter empolyees dept (ABC): ";
cin >> employee.dept;
}
void printEmployeeRecord(Employee staff){
cout << "Wage: Status: Department:" <<endl;
cout << fixed << setprecision( 2 ) << staff.wage;
}
First, try searching google for "passing parameters by reference and by value".
You'll learn that:
void readEmpoyeeRecord(Employee staff);
passes your variable to the function by value, meaning that a copy of your object is created and used inside the function, so your original object doesn't get modified, but a copy.
To get the desired result, use:
void readEmpoyeeRecord(Employee& staff);
Passing by reference means you pass that exact same object, and not a copy.
Your code will basically work like this:
//create new employee
Employee employeeA;
//call method readEmployeeRecord on a copy of employeeA
readEmpoyeeRecord(employeeA);
//call method printEmployeeRecord on a copy of employeeA
printEmployeeRecord(employeeA);
readEmpoyeeRecord(Employee employee) is copy by value, not reference, so you are loosing your changes.
Use readEmpoyeeRecord(Employee& employee) instead.
Your problem is that in C++, objects are passed by value until you specify otherwise. Thus, in the body of readEmpoyeeRecord you're dealing with a copy of employeeA, not with employeeA itself.
Pass a reference to your readEmpoyeeRecord function. The signature of readEmpoyeeRecord should read:
void readEmpoyeeRecord(Employee &employee)