How to set a custom variable name through a function argument - c++

So what i am trying to do is basically get the second argument of a function, and making the second argument the name of a variable so i can easily store the users input. Here is my code
`
#pragma once
#include <iostream>
using namespace std;
void askAndStore(string question, string variable)
{
cout << question + " ";
cin >> variable;
}
`

Pass variable by reference:
void askAndStore(string question, string& variable)
{
cout << question + " ";
cin >> variable;
}
string& instead of string. Without using & you'd be passing in a copy of your varaible, using a reference type string& you pass the actual variable in which is then modified by cin >> variable;.
P.S Don't use using namespace std;

You can't do this in C++.
You could have a std::map<std::string, SomeType> that you populate with your read-in names.
#pragma once
#include <iostream>
#include <map>
#include <string>
class Values
{
std::map<std::string, std::string> values;
public:
void askAndStore(std::string question, std::string name)
{
std::cout << question << " ";
std::cin >> values[name];
}
std::string get(std::string name)
{
return values[name];
// or return values.at(name); if name must already exist in values
}
};
int main()
{
Values user;
user.askAndStore("What is your name?", "usersName");
}
That assumes your values are std::strings

Related

Operators Not Working With Class Objects?

I'm trying to learn C++ and I'm creating small little programs to test out how it works. I made this code but for some reason I get this error on compiling:
binary '>>': no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
If anyone could help me figure this out I would appreciate it.
Code:
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <string>
#include "logo.h"
class classTest
{
public:
void setName(std::string x)
{
name = x;
}
std::string getName()
{
return name;
}
private:
std::string name;
};
int main()
{
SetConsoleTitle("plains.exe");
displayLogo();
std::cout << "Please enter your name: ";
classTest testObject;
std::cin >> testObject.setName;
std::cout << "Your name is " << testObject.getName() << "." << std::endl;
return 0;
}
setName is a function. So, you can not use cin >> testObject.setName. You can either do this-
string name;
cin >> name;
testObject.setName(name);
or use Operator Overloading to overload >>.
You are calling the instream operator on a void function
std::cin >> testObject.setName;
You need to first take the input in a string like and then call the setter to set the value
string inputName;
std::cin>>inputName;
testObject.setName(inputName);

How do you declare a stack of type struct? in c++

In the code below, how do you properly declare a stack of type struct and push strings onto the stack so that they are saved in the struct? How do you specify where you want to push the variable into a certain variable of the struct? The line that is causing an error is commented. Thanks!
#include <iostream>
#include <stack>
using namespace std;
struct purchasedItem
{
string Name;
float Cost;
};
int main()
{
stack<purchasedItem> shoppingBasket;
string word=" ";
cout << "Enter some items:" << endl;
while(word!="quit")
{
cin >> word;
shoppingBasket.push(word); // this line causes an error
}
return 0;
}
I would recommend using std::stack for such operations: http://en.cppreference.com/w/cpp/container/stack

C++ Passing vectors to an overloaded class - some call statements work, some do not.

I have spent a great deal of time in google trying to figure out how to pass a vector when using .h and .cpp files between a call in main and a function in an includes block. I was successful using class definitions.
Now everything is going fine until I want to create an overloaded function. (I could have done this with two different classes, but I must use one overloaded function in my program.)
Here is my writeData.h file:
#ifndef WRITEDATA_H
#define WRITEDATA_H
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class writeData
{
public: writeData();
public: writeData(vector<int> & DATAFILE);
public: writeData(vector<int> & DATAFILE, string);
};
#endif
The placement of the using namespace std; is another topic.
Here is my writeData.cpp file:
#include "writeData.h"
writeData::writeData()
{
std::cout << "Default writeData" << std::endl;
}
writeData::writeData(vector<int> & DATAFILE)
{
cout << "writeData 1" << endl;
for (int var : DATAFILE)
{
cout << var <<endl;
}
}
writeData::writeData(vector<int> & DATAFILE, string fileName)
{
ofstream myfile(fileName);
cout << "writeData" << endl;
if (myfile.is_open())
{
for (int var : DATAFILE)
{
cout << var << endl;
myfile << var << endl;
}
myfile.close();
}
}
And here is my main function:
#include <iostream>
#include <vector>
#include <string>
#include "writeData.h"
using namespace std;
int main()
{
string fileName = "test.txt";
vector<int> items{ 10, 14, 22, 34 };
writeData();//default
///////////////////////////////////////////////////
// the next line is the problem code:
//writeData(items);//writes to screen only
//<<When I uncomment it the compiler Tosses the following:
// 'items': redefinition; different basic types
////////////////////////////////////////////////////
writeData(items, fileName);//writes to screen and to file
cin.ignore();
cin.get();
}
The offending line is writeData(items);
Any assistance or pointers to online articles would be most appreciated.
The immediate issue is that this declaration
writeData(items);
is the same as
writeData items;
hence the redefinition error. The deeper issue is that you have defined three constructors for a class, and seem to be attempting to call them without making a named instance. To succesfully call the one parameter constructor passing items, you'd need something like
writeData data_writer(items);
Alternatively, you may want either member functions, or non-members. The choice would depend on whether you really want to model a class, which maintains certain invariants or not. An example of members,
class writeData
{
public:
void write_data() const;
void write_data(const vector<int> & DATAFILE) const;
void write_data(const vector<int> & DATAFILE, string) const;
};
Then
WriteData wd;
wd.write_data(items);
Example of non-members:
namespace writeData
{
void write_data();
void write_data(const vector<int> & DATAFILE);
void write_data(const vector<int> & DATAFILE, string);
};
Then
writeData::write_data(items);
Note I have made the vector<int> parameters const reference because they are not being moified in the functions.

How Do I Store Objects in a Object in a Vector? (C++)

I hope this is not a stupid question. Basically I would like to access a string stored in a Class (Statement is the name I am using) in a vector of type Statement. Basically I am trying to store objects in a dynamic hierarchy of objects.
Types.cpp:
#include<iostream>
#include<fstream>
#include <string>
#include <vector>
using namespace std;
class Statement{
public:
vector<string> Inner_String;
vector<Statement> Inner_Statement;
string contents;
void set_contents (string);
string get_contents(){ return contents;}
void new_string(string);
string get_string(int v){return Inner_String[v];}
void new_Inner_Statement(Statement);
Statement get_Inner_Statement(int v){return Inner_Statement[v];}
};
void Statement::set_contents(string s){
contents = s;
}
void Statement::new_string(string s){
Inner_String.push_back(s);
}
void Statement::new_Inner_Statement(Statement s){
Inner_Statement.push_back(s);
}
Main method:
#include <iostream>
#include "FileIO.h"
#include "Types.h"
using namespace std;
int main()
{
Statement test;
test.new_Inner_Statement(Statement());
Statement a = test.get_Inner_Statement(0);
a.set_contents("words");
cout << a.get_contents();
test.get_Inner_Statement(0).set_contents("string");
cout << test.get_Inner_Statement(0).get_contents();
return 0;
}
What happens is
cout << a.get_contents()
returns its string while
cout << test.get_Inner_Statement(0).get_contents()
does not.
Look at this piece of code:
test.get_Inner_Statement(0).set_contents("string");
^^^^^^^^^^^^^^^^^^^^^^^^^^^
It calls this function:
Statement get_Inner_Statement(int v)
which returns a copy object (temporary) of type statement. On this object, you calls set_contents function, at which cease to exists at the end of the call.
Then, you call:
test.get_Inner_Statement(0).get_contents();
that creates a new temporary, from the unchanged statement, and try to get its contents.

Could not separate implementation and interface

I am unable to compile the following files.
I am trying to pass the name and age to an object and after checking and assigning each age to proper category(adult, kid...) then i am trying to print it.
My 3 files are following:
The first 1:
//cannot access private member declared in class Person
//No constructor could take the source type, or constructor overload resolution was ambiguous.
#include <iostream>
#include <string>
using namespace std;
#include "person2.h"
void getData(Person&);
void displayData(Person&);
int main(){
Person p;
getData(p);
displayData(p);
}
void getData(Person& p){
cout<< "Enter the name: ";
cin>> p.name;
cout<<"Enter the age: ";
int age;
cin>> age;
p.setAge(age);
p.ageGroup = p.determineAgeGroup(age);
}
void displayData(Person& p){
cout<<p.name<< " is in the group of " << p.ageGroup <<endl;
}
The second one:
#include <iostream>
#include <string>
using namespace std;
class Person {
public:
string name;
string ageGroup;
void setAge(int&);
string getAge();
string getAgeGroup(int);
private:
int age;
string determineAgeGroup(int );
};
The third one:
#include <iostream>
#include <string>
#include "person2.h"
using namespace std;
void Person::setAge(int& a){
if(a<0) cout<< "No";
}
string Person::getAge(){
return age;
}
string Person::determineAgeGroup(int a){
if(a>= 65) return "Senior";
else if(a<65 & a>= 20) return "Adult";
else if(a<20 & a>= 13) return "Teen";
else return "Kid";
}
string Person::getAgeGroup(int a){
return determineAgeGroup(a);<<endl;
}
Check the following:
endl instead of end in displayData
declare int age in getData and pass that value to p.setAge
return value from getAge should be an int
make determineAgeGroup() public or call determineAgeGroup() from a member function like setAge() or call your public function getAgeGroup().
This should at least get you compiling...
Note: The final edit that solved the problem was bullet point number 4, in particular calling the public function getAgeGroup().