I am learning C++ and was wondering if there is an equivalent to assigning a user input to a variable in one line, like you can do in C# for example:
string foo = Console.ReadLine();
I was hoping that one of these would work, but they don't.
const string foo = cin >> foo;
cin >> const string foo;
Ideally the variable should be a constant, but that's not necessarily a requirement.
Are there ways of one lining it in C++ or will I just have to learn to live with this?
double foo = 0;
cin >> foo;
As apple apple says you can write your own functions
double console_read_double()
{
double x = 0.0;
cin >> x;
return x;
}
int main()
{
double y = console_read_double();
double z = console_read_double();
...
}
However one advantage of the C++ way is that you can chain calls to input functions
int main()
{
double y, z;
cin >> y >> z;
...
}
You can't do that with a function call that returns the value read.
Another advantage is that you can test the success or failure of the operation with a single line of code
int main()
{
double y, z;
if (cin >> y >> z)
{
// success
}
else
{
// handle error
}
}
Sorry but there is no way in C++ to do this in one line. Unless you do this when you are using an if statement:
if(double b = 0; std::cin >> b)
{
// Code
}
otherwise you will have to live with:
double b = 0;
std::cin >> b;
Or you can just make a function like this:
auto init_and_input()
{
double b = 0;
std::cin >> b;
return b;
}
and then:
int main()
{
auto x = init_and_input();
}
So your answer is not really if you include the function.
In addition to what has been stated, and in the ultra specific scenario where you need to get only one character, standard library provide the function get() that reads and return one character in a stream. This allows you to initialize your variable with the read value, therefore you could also define it as a const.
#include <iostream>
int main()
{
const char some_char = std::cin.get();
// Do whatever with some_char
return 0;
}
Note that even if it is theoretically valid C++, this doesn't looks like any kind of good practice, and it might be preferable in almost every case to just stick to another, most common, way to read your stream.
Related
Lets say I have a loop that inputs a value from user, and if the value is equal to zero, it breaks.
Is there a way to do this without writing the same condition twice?
for example:
int x;
do
{
std::cin >> x;
if (x)
{
//code
}
} while(x);
What is the cleanest way to do this?
It's probably cleanest to write a little function to read the value, and return a boolean to indicate whether you read a non-zero value, then use that function:
bool read(int &x) {
std::cin >> x;
return std::cin && (x != 0);
}
while (read(x)) {
// code to process x
}
When you write the code exactly as you described it with words it get's simpler:
int x;
while(std::cin >> x) // I have a loop that inputs a value from user, and ...
{
if(x == 0) // if the value is equal to zero, ...
{
break; // it breaks.
}
// do something with x ...
}
The reason for having std::cin >> x; as condition is to stop reading when invalid input is entered or the stream ends.
The most laconic way (and note how it tests the integrity of the input stream) is
while (int x; std::cin >> x && x){
// code
}
Another approach, which gives you a bit more scope for introducing code for the fail condition, is
for (;;){ // infinite loop idiom
int x;
if (std::cin >> x && x){
// code
continue; // i.e. go round again
}
// ToDo - code here?
break;
};
is one way. This is not to everyone's taste although the break; before the end of the loop body gives some comfort that the loop is not really infinite.
It also has the advantage that the scope of x is not leaked to the outer scope.
Verbatim "a loop that inputs a value from user, and if the value is equal to zero, it breaks."
while (true)
{
std::cin >> x;
if (x == 0)
break;
...
}
How about:
int x;
while (std::cin >> x, x) {
std::cout << x*5 << std::endl;
}
No ifs, no breaks, the x is already evaluated to be non-zero by the while condition.
I have a base class (robot) and depending on the arguments passed to the program I want to downcast the robot pointer to a specific derived class. the robot class has virtual functions which are defined in each of the derived classes.
So far I can create a pointer of the base class, and within a conditional statement, create a derived class which the base is then dynamically cast to. Within the conditional the pointer works as intended but after leaving the conditional statement the derived class is out of scope and the functions go back to virtual. Is there a way I can keep the pointer to the derived class?
class vehicles{
public:
virtual void print_state(int state_ind, ofstream& file){}
};
class hovercraft : public vehicles{
public:
hovercraft(
int L_in, int W_in,
double start_x, double start_y,
double goal_x, double goal_y)
{
L = L_in;
W = W_in;
start_state.x = start_x;
start_state.y = start_y;
goal_state.x = goal_x;
goal_state.y = goal_y;
Tree.push_back(start_state);
}
void print_state(int state_ind, ofstream& file){
state s = Tree[state_ind];
file<<s.phi<<","<<
s.u<<","<<
s.v<<","<<
s.r<<","<<
s.x<<","<<
s.y<<"\n";
}
private:
struct state{
double g=0;
double u=0;
double v=0;
double r=0;
double x=0;
double y=0;
double phi=0;
int p=0;
};
int L,W;
state start_state, goal_state, state_sample;
vector<state> Tree;
};
int main(int argc, char* argv[])
{
ifstream infile;
string vehicle_name;
vehicles* vehicle;
int start, goal;
for(int i=0; i < argc; i++){
if (string(argv[i])=="-m"){
infile.open (argv[i+1]);
} else if (string(argv[i])=="-v"){
vehicle_name = string(argv[i+1]);
}
}
ofstream file_out;
file_out.open ("state.csv");
if(vehicle_name == "hovercraft"){
int L, W;
double start_x, start_y, goal_x, goal_y;
infile >> L;
infile >> W;
infile >> start_x;
infile >> start_y;
infile >> goal_x;
infile >> goal_y;
hovercraft my_vehicle(L,W, start_x, start_y, goal_x, goal_y);
hovercraft* vehicle = dynamic_cast<hovercraft*>(&my_vehicle);
} else {
cout<<"Invalid Vehicle: "<<vehicle_name<<"\n Exiting...\n";
return 0;
}
vehicle->print_state(0);
}
This is simplified from the actual code but I think it captures the issue. The result I want is for print to work the same inside the if statement and after it but after it will always print "no vehicle".
You're overloading the variable rptr inside the scope of your if-statements, which hides the one declared at the top of main. Your final rptr->print() is therefore undefined behavior, because you're calling a virtual function on an uninitialized pointer.
Simply remove the overloading as follows:
robot *rptr = nullptr;
if (*argv[1] == 'h') // <-- also fixed this (yours was broken)
{
rptr = new hovercraft();
rptr->print();
}
else if (*argv[1] == 'q') // <-- also fixed this (yours was broken)
{
rptr = new quadrotor();
rptr->print();
}
else
{
std::cout << "Invalid vehicle input" << std::endl;
}
if (rptr)
{
rptr->print();
}
You might also want to consider using std::shared_ptr or std::unique_ptr (along with std::make_shared or std::make_unique) to correctly manage the lifetime of dynamic memory.
class boundaryPt{
public:
friend class KCurvature;
int x;
int y;
boundaryPt(int x, int y){
this->x = x;
this->y = y;
}
boundaryPt(){}
};
class KCurvature{
public:
boundaryPt* boundaryPtAry;
int numPts;
ifstream input;
KCurvature(char* inFile){
input.open(inFile);
input >> numPts;
boundaryPtAry = new boundaryPt[numPts];
}
void loadData(char* inFile){
input.open(inFile);
int x;
int y;
while(!input.eof()){
input >> x;
input >> y;
boundaryPtAry[index++] = new boundaryPt(x,y);
}
};
My issue is with:
boundaryPtAry[index++] = new boundaryPt(x,y);
I'm trying to store my boundaryPt objects in my array of type boundaryPt, but since I declared that array as boundaryPt* it wont let me a store a boundaryPt.
Is this a simple issue of deferencing a pointer? I'm rusty with C++.
SOLVED! I realize now that when creating an array of objects, you are not just creating an array, but the objects themselves as well. So there was no need to create a new object and try and put it in the array(or in my case have the array index point to it).
while(!input.eof()){
input >> boundaryPtAry[index].x;
input >> boundaryPtAry[index].y;
index++;
}
I want to create code that will help me get numbers bigger than MAXINT. I heard about that I can use Binary Code Decimal to do this, and then every two of decimal numbers(converted to BCD) of the bigger number keep in char. But how to do this? I should give string as input, then convert somehow to BCD every single decimal number? And how can I put two converted decimal numbers to one char? I'm new in C++ and don't know how can i do it.
P.S. I don't want to use libraries which are "special" for that kind of problems.
As it turns out, this is actually quite simple. How about we try to take it to the next level?
Below is an implementation of a BCD number with infinite(or as much as memory can hold) size. It only supports positive integer numbers. I'll leave extending this to support negative numbers(or real numbers) as an exercise.
First things first: Yes, we want to get our number as a string and then build it up from that. Since it's only an integer, this is actually quite easy to do. We primarily create a helper function to aid us in identifying all the digits.
int char_to_int(const char c) {
int ret = c - '0';
if(ret > 9 || ret < 0) throw 1; // for simplicity. Use a class derived from std::exception instead.
return ret;
}
We can now try to implement input and output for our big number.
First Try
Having that helper guy, turning a string to a BCD-encoded buffer is easy. A common implementation may look like this:
int main() {
unsigned char bignum[10]; // stores at most 20 BCD digits.
std::memset(bignum, 0, sizeof(bignum));
std::string input;
std::cin >> input;
try {
if (input.size() > 20) throw 1; // Avoid problems with buffer overflow.
for (int i=1;i<=input.size();i++) {
int n = char_to_int(input[input.size()-i]);
bignum[sizeof(bignum) - (i+1)/2] |= n << (i%2)*4; // These are bitwise operations. Google them!
}
}
catch(int) {
std::cout << "ERROR: Invalid input.\n";
return 0; // Exit cleanly.
}
// bignum is now filled. Let's print it to prove.
for (int i=0;i<sizeof(bignum);i++) {
int first_digit = bignum[i] & '\x0F'; // Right side, doesn't need to shift.
int second_digit = (bignum[i] & '\xF0')>>4; // Left side, shifted.
std::cout << first_digit << second_digit;
}
}
This is not very space-efficient, however. Note that we have to store all the 20 digits, even if our number is small! What if we needed 1000 digits? What if we need 1000 numbers that may or may not have these 1000 digits? It is also error-prone: Look that we had to remmember to initialize the array, and do a bounds check before conversion to avoid a buffer overflow.
Second Try
We can improve our implementation using a std::vector:
int main() {
std::vector<unsigned char> bignum; // stores any quantity of digits.
std::string input;
std::cin >> input;
try {
// For an odd number of digits we want a trailling zero at the end.
if(input.size()%2) n.num_vec.push_back(char_to_int(input[0]));
for (unsigned i=input.size()%2;i<input.size();i+=2) {
int left = char_to_int(input[i]);
int right = char_to_int(input[i+1]);
n.num_vec.push_back(0);
n.num_vec.back() = left << 4;
n.num_vec.back() |= right;
}
}
catch(int) {
std::cout << "ERROR: Invalid input.\n";
exit(0); // Exit cleanly.
}
// bignum is now filled. Let's print it to prove.
for (unsigned i=0;i<bignum.size();++i) {
// Notice that we inverted this from the previous one! Try to think why.
int first_digit = (bignum[i] & '\xF0')>>4; // Left side, shifted.
int second_digit = bignum[i] & '\x0F'; // Right side, doesn't need to shift.
if(i || first_digit) std::cout << first_digit; // avoid printing trailling 0.
std::cout << second_digit;
}
}
Lookin' good, but that is too cumbersome. Ideally, the bignumber user shouldn't have to deal with the vector positions and all that mumbo-jumbo. We want to write code that behaves like:
int main() {
int a;
cin >> a;
cout << a;
}
And it should just work.
Third Try
Turns out this is possible! Just wrap bignum into a class, with some helpful operators:
class bignum {
std::vector<unsigned char> num_vec;
template<typename T>
friend T& operator<<(T& is, bignum& n);
template<typename T>
friend T& operator>>(T& os, bignum& n);
};
// Get input from any object that behaves like an std::istream (i.e.: std::cin)
template<typename T>
T& operator>>(T& is, bignum& n) {
std::string input;
is >> input;
n.num_vec.reserve(input.size());
if(input.size()%2) n.num_vec.push_back(char_to_int(input[0]));
for (unsigned i=input.size()%2;i<input.size();i+=2) {
int left = char_to_int(input[i]);
int right = (i+1) != input.size()?char_to_int(input[i+1]):0; // If odd number of digits, avoid getting garbage.
n.num_vec.push_back(0);
n.num_vec.back() = left << 4;
n.num_vec.back() |= right;
}
return is;
}
// Output to any object that behaves like an std::ostream (i.e.: std::cout)
template<typename T>
T& operator<<(T& os, bignum& n) {
for (unsigned i=0;i<n.num_vec.size();++i) {
int first_digit = (n.num_vec[i] & '\xF0')>>4; // Left side, shifted.
int second_digit = n.num_vec[i] & '\x0F'; // Right side, doesn't need to shift.
if(i || first_digit) os << first_digit; // avoid printing trailling 0.
os << second_digit;
}
return os;
}
Then our main function looks much more readable:
int main() {
bignum a;
try {
std::cin >> a;
}
catch(int) {
std::cout << "ERROR: Invalid input.\n";
return 0; // Exit cleanly.
}
std::cout << a;
}
Epilogue
And here we have it. Of course with no addition, multiplication, etc. operators, it isn't very useful. I'll leave them as an exercise. Code, code and code some more, and soon this will look like a piece of cake to you.
Please feel free to ask any questions. Good coding!
I am sure this is a very simple fix and I feel dumb asking it but here it goes.
I need help with a struct and passing info from a gather function to a save or set function, and then passing it again to another function for further use.
Basically, it looks like this to start. I'll just add short snips of the code. All can be provided if you would like to see it.
I right now am just looking for the proper way to pass struct defined data from get.... to set.... functions.
struct printype
{
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
};
int getunknown15(); // prototypes
int setunknown15(int);
then we have a simple main.
int main()
{
printype pt;
pt.unknown15=getunknown15();
pt.unknown15=setunknown15(12);
pt.serial11_14=getserial11_14();
pt.serial11_14=setserial11_14("12345678");
pt.year8=getyear8();
pt.year8=setyear8(44);
pt.month7=getmonth7();
pt.month7=setmonth7(11);
pt.day6=getday6();
pt.day6=setday6(12);
pt.hour5=gethour5();
pt.hour5=sethour5(12);
pt.minute2=getminute2();
pt.minute2=setminute2(23);
cout <<"-----------------------------------------------------"<<endl;
cout <<" Let's Get Started"<<endl;
cout <<"-----------------------------------------------------"<<endl;
setup(pt.dots); // sets up the array
dpinfo(pt); // prints out the final array
ftarray(pt);
spar(pt.dots);
darray(pt.dots);
}
and finally the get and set array functions.
int getunknown15()
{
printype tem;
cout <<"-----------------------------------------------------"<<endl;
cout <<" Enter the Unkown Variable (0-127): ";
cin >>tem.unknown15;
cout <<"-----------------------------------------------------"<<endl;
return tem.unknown15;
}
next is
int setunknown15(int tem)
{
printype pp;
if (tem>127||tem<0)
{
cout << "Error" << endl;
return 0;
}
else
{
pp.unknown15 = tem;
return pp.unknown15;
}
}
I hope this isn't too much to read and understand
Anyway, I know this has a really simple answer but my brain just isn't working right now.
Edit: As StilesCrisis stated, Send struct as parameter is quiet stupid in this case. better use a const reference.
Well, I am not sure if I understand your question correctly. You can simply send struct to another function as parameter, or as a pointer.
like:
void SetStruct(const printype& var);
printype GetStruct();
Is it what you are looking for?
Please use the following access to the your fields, (by reference):
struct printype *myPtr = new printype;
myPtr->day6 = 43;
When use pointer instead of a normal variable, you should use -> instead . to access your fields.
I know this is kind of old but I thought I should give it a shot, since you are using C++ and it looks like you are trying to use some OO practices (I think), you don't need to start with a struct, even though OO principles can be applied using them as well though not as elegantly.
you can define your class header file as such.
#ifndef PRINTYPE_H
#define PRINTYPE_H
#include <string>
using namespace std;
class printype
{
private: // we always want to declare our member fields private for safety/managements reasons, no one will be able to access them outside.
char dots[8][15];
int unknown15; // can have values of 0..127
string serial11_14; // 8 characters 00000000...99999999
int year8; // without century, 0..99
int month7; // 1..12
int day6; // 1..31
int hour5; // 0..23
int minute2; // 0..59
void init(); // This is the method we use to initialize our starting state.
public: // This is our public methods, how people deal with/get/set our state.
printype(); // This is our default constructor
printype(const printype& print_type); // This our copy constructor
virtual ~printype(); // This is our destructor, its virtual, making safer for inheritance.
// This is our setters/getters
void setUnknown(int unknown);
int getUnknown();
void setYear(int year);
int getYear();
void setMonth(int mont);
int getMonth();
// and well you get the idea, you can add more methods.
};
#endif
and the accompanying class source file with your functions implementation
printype::printype()
{
this->init(); // Initialize all your vatiables, safer to just define a function to this.
}
printype::printype(const printype& orig) // copy constructor
{
this->setUknown(orig.getUnknown());
this->setDay(orig.getDay());
this->setDots(orig.getDots());
// you get the idea ...
}
printype::~printype()
{
// Have anything you need to do before destroying the object.
}
void printype::init()
{
this->setUnknwon(0);
this->setyear(0);
this->setMonth(1);
char dots[8][15] = {'\0'};
this->setDots(dots);
// you get the idea, you want to initialize all your variables since, for the most part they initially hold garbage.
}
void printype::setUnknown(int unknown)
{
if (unknown >= 0 && unknown < 127)
this->unknown15 = unknown;
else
error("Expecting unknown to be between 0 and 127"); // error should probably print the error and/or exit(-1) up to u
}
int printype::setYear(int year)
{
if (year >= 1 && year <= 99)
this->year8 = year;
else
error("Expecting year between 0 and 99"); // you may want to implement an error function!
}
int printype::getYear()
{
return this->year8;
}
void printype::setDots(char dots[8][15])
{
// you may want to do some verifications
memcpy(this->dots, dots, sizeof(dots));
}
void printype::setDots(char **dots) // this is a bit unsafe, use at your own risk.
{
if (dots)
{
unsigned int index = 0;
for (index = 0; index < 8; index++)
if (dots[index])
memcpy(this->dots[index], dots[index], 15);
else
error("dots required pointer ...");
}
else
error("dots required pointer ...");
}
char **getDots() // We will be returning a copy, we don't want the internal state to be affected, from outside, by using reference or pointers.
{
char **dots = new char*[8];
unsigned int index = 0;
for (index = 0; index < 8; index++)
{
dots[index] = new char[15];
memcpy(dots[index], this->dots[index], 15);
}
return dots;
}
// and well you get the idea ...
to use your class
printype *print_type_p = new print_type();
// or
printype pront_type_p();
// use the different public method to update the internal state.
print_type_p->setYear(3);
// or
print_type.setYear(3);
print_type_p->getYear();
// and so on.