Declaring 2 variables - c++

I would like to ask if it would be possible to declare 2 variables on one line like above (on the same line):
#include <iostream>
#include <string>
using namespace std;
string a, double b;
int main()
{
return 0;
}

Your declaration has the wrong syntax.
string a, double b;
should be string a; double b;.
If you want to declare two variables with a comma they need to have the same type.

Same variable types: YES
Different variable types: NO
Different variables need to be on different lines OR separated with a semicolon ; as it signals a new line e.g.
int a; double b; bool c;
Which is the same as,
int a;
double b;
bool c;
If they're the same type you can use a comma , e.g.
int a, b, c;

Related

Is it possible to declare a variable inside an "if" statement?

I want to declare a variable inside an "if" statement and do something about the variable after the "if" statement. Here is my simplified code:
#include <iostream>
using namespace std;
int main() {
int a;
cin >> a;
if (a==1)
string b;
else
int b;
cin >> b;
//and some long codes using variable b
}
Is it possible to do this? What should I do to declare a variable with different data types(under different conditions) by using the same variable name?
No.
You cannot have a global scope for the variable you declare inside any local code block. The variables are local to the block it is declared in.
But you can think of using functions for "long_code_block_using_b" that you call inside the same block as the variable being declared
again if you do the same thing for all data types you can use function templates as below.
#include <iostream>
using namespace std;
template <typename T>
T long_code_using_variable_b()
{
T b;
cin >> b;
//and some long codes using variable b
return b;
}
int main() {
int a;
cin >> a;
if (a==1)
cout << long_code_using_variable_b<string>();
else
cout << long_code_using_variable_b<int>();
}

C++ How to pass two structs from function?

Here's the main function ex1-1.cpp
#include <iostream>
#include "ex1-1.h"
using namespace Complex;
int main(int argc, char *argv[])
{
Cplex a={0.0,0.0}, b={0.0,0.0},c={0.0,0.0}, d={0.0,0.0};
// use struct named Cplex under namespace Complex
ReadTextFile(argv[1], a, b);// process text file
std::cout<<a.real<<std::showpos<<a.image<<std::endl;
std::cout<<b.real<<std::showpos<<b.image<<std::endl;
return 0;
}
one header ex1-1.h
#include <iostream>
#include <fstream>
namespace Complex
{
typedef struct
{
double real;
double image;
}Cplex;
Cplex ReadTextFile(char argv[],Cplex a,Cplex b);
}
and one for functions ex1-1-function.cpp
#include<iostream>
#include<fstream>
#include<iomanip>
#include "ex1-1.h"
namespace Complex
{
Cplex ReadTextFile(char argv[],Cplex a,Cplex b)
{
std::ifstream fin;
fin.open("complex.txt");
char i;
fin>>a.real>>a.image>>i;
fin>>b.real>>b.image>>i;
std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;
return (a,b);
};
}
the text file complex.txt looks like this
1.5+6i
-2-10i
I tried to define a type of structure called Cplex, including two members, real and image
declare Cplex a and Cplex b
then use function ReadTextFileread(argv[1],a,b) to read in two complex numbers and store in the structures a and b
then return a and b at once
But no matter how I tried the main function can only read b instead of both
How can I pass two structures to the main function at once?
Or should I use Array to contain two structures then pass it?
You can use std::pair to couple two values together:
std::pair<Cplex> ReadTextFile(char argv[])
{
Cplex a, b;
...
return { a, b };
};
Then use them like this:
#include <tuple>
...
Cplex a, b;
std::tie(a, b) = ReadTextFile(argv);
Note that std::tie is only available since C++11.
Or if you can use C++17 it will be even simpler to use structured binding:
auto [a, b] = ReadTextFile(argv);
In C & C++ you can return only one value from the function.
Instead use pass by reference to pass the structs 'a' and 'b' and then fill the values within the function.
Declaration:
void ReadTextFile(char argv[],Cplex &a,Cplex &b);
Definition:
void ReadTextFile(char argv[],Cplex& a,Cplex& b)
{
std::ifstream fin;
fin.open("complex.txt");
char i;
fin>>a.real>>a.image>>i; // values filled here can now be read in the caller i.e main.
fin>>b.real>>b.image>>i;
std::cout<<std::noshowpos<<a.real<<std::showpos<<a.image<<"i"<<std::endl;
std::cout<<std::noshowpos<<b.real<<std::showpos<<b.image<<"i"<<std::endl;
return;
};
Hope this helps.

c++ error no instance of constructor

I'm new to C++ and trying just to return values passed through the constructor, I am not sure what I have done wrong on the below code it keeps giving me an error: no instance of constructor..matches, cannot convert parameter 3 from 'const char [5]' to 'int'
#include <iostream>
#include <string>
using namespace std;
class TestClass{
string a;
string b;
int x;
public:
TestClass(string m, string n, int y){
this->a = m;
this->b = n;
this->x = y;
}
int test(){
return this->x;
}
};
int main(){
TestClass *a = new TestClass("test1","test2","9999");
cout<<a->test()<<endl;
}
You are passing the number 9999 as "9999" -- the quotes around it denote it is a string. Simply pass it as 9999.
You have to change your third parameter from "9999" to 9999. The quotes say you're treating it as a string when in fact the constructor is expecting an int.

How to include a declaration in the comma operator?

I have two simple testing lines:
cout<<(cout<<"ok"<<endl, 8)<<endl;
cout<<(int i(8), 8)<<endl;
The first line worked, but the second failed compilation with
error: expected primary-expression before 'int'
For some reason, I do need a declaration in the comma operator. To be more specific, I want to declare some variables, obtain their values, and assign them to my constant class members from the initialization list of my class constructor. Following shows my intentions. If not achievable using comma operator, any another suggestions?
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;
void readFile(const string & fileName, int & a, int & b)
{
fstream fin(fileName.c_str());
if (!fin.good()) {cerr<<"file not found!"<<endl; exit(1);}
string line;
getline(fin, line);
stringstream ss(line);
try {ss>>a>>b;}
catch (...) {cerr<<"the first two entries in file "<<fileName<<" have to be numbers!"<<endl; exit(1);}
fin.close();
}
class A
{
private:
const int _a;
const int _b;
public:
A(const string & fileName)
:
_a((int a, int b, readFile(fileName,a,b), a)),
_b((int a, int b, readFile(fileName,a,b), b))
{
/*
int a, b;
readFile(fileName,a,b);
_a = a;_b = b;
*/
}
void show(){cout<<_a<<" "<<_b<<endl;}
};
int main()
{
A a("a.txt");
a.show();
}
Declarations are statements and not expressions. You cannot place statements inside of expressions, though you can place expressions inside of statements. Accordingly, you cannot declare a variable in the way that you're describing above. You'll need to separate it out into multiple different statements.
I would be surprised if if you actually needed to do this. If you do, there is probably something problematic about your design.
Hope this helps!
You should have a look at Boost Phoenix (which has phoenix::let to do roughly this). Bear in mind, Phoenix is an eDSL, really (embedded domain specific language).
You could do an ugly trick and abuse lambdas:
cout<< ([]->int{ int i(8); return 8; })() <<endl;
A lambda allows a declaration within an expression. So this is possible:
std::cout << ([]{ int i(8); m_i = i; }(), 8) << std::endl;
But it's really weird - I assume this will be in some #define macro that makes it appear closer to normal.
You cannot. This is unpossible in C++. The fact that you are trying to do this is also a code smell. Something's not right here.
I want to declare some variables, obtain their values, and assign them
to my constant class members from the initialization list of my class
constructor. Not sure how to achieve this.
You didn't say what you intended to do with these variables you declare after you've used the values, but I'm guessing that once you've finished with the values, you've finished with the variables. In other words, they are temporary.
Your edited example suggests that my assumption is correct. It also confirms the code smell. Based on your (intended) code, you are going to read the file twice.
I'd say the most straightforward way to do this is to use an intermediary, kind of like a factory class. This also has the benefit of being able to read the file only once, as opposed to twice as you are doing now.
void readFile (const std::string& fileName, int& a, int& b)
{
// some magic
a = 42;
b = 314;
}
class FileReader
{
public:
FileReader (const std::string fileName)
:
mFileName (fileName),
mA (42),
mB (314)
{
// something happens like reading the file
}
int GetA () const
{
return mA;
}
int GetB () const
{
return mB;
}
private:
int mA;
int mB;
std::string mFileName;
};
class A
{
private:
const int mA;
const int mB;
public:
A (const FileReader& reader)
:
mA (reader.GetA()),
mB (reader.GetB())
{
}
};
Using this FileReader is simple:
int main()
{
A myA (FileReader ("somefile.txt"));
}

Namespace Scope Question

I have a quick question about namespace scope:
I have two namespaces, A and B, where B is nested inside A.
I declare some typedefs inside A.
I declare a class inside B ( which is inside A )
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
ie:
B.hpp:
using namespace A;
namespace A {
namespace B {
class MyClass {
typedeffed_int_from_A a;
};
}
}
This seems redundant... Is this correct?
To access the typedefs (declared in A), from inside B, do I need to do "using namespace A;"
No.
However if there is a typedef or some other symbol with same name as your typedef, defined in the namespace B, then you need to write this:
A::some_type a;
Lets do a simple experiment to understand this.
Consider this code: (must read the comments)
namespace A
{
typedef int some_type; //some_type is int
namespace B
{
typedef char* some_type; //here some_type is char*
struct X
{
some_type m; //what is the type of m? char* or int?
A::some_type n; //what is the type of n? char* or int?
};
void f(int) { cout << "f(int)" << endl; }
void f(char*) { cout << "f(char*)" << endl; }
}
}
int main() {
A::B::X x;
A::B::f(x.m);
A::B::f(x.n);
return 0;
}
Output:
f(char*)
f(int)
That proves that type of m is char* and type of n is int as expected or intended.
Online Demo : http://ideone.com/abXc8
No, you don't need a using directive; as B is nested inside of A, the contents of A are in scope when inside B.