This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed last month.
why does the below function (f) work when i put cout in the function body but does't work when
i put cout after the function call
#include <iostream>
using namespace std;
void f(string str)
{
int size=str.size();
for (int i=0;i<size/2;i++)
{
char temp=str[i];
str[i]=str[size-i-1];
str[size-i-1]=temp;
}
}
int main ()
{
string a="abcd";
f(a);
cout<<a; //output: abcd
}
#include <iostream>
using namespace std;
void f(string str)
{
int size=str.size();
for (int i=0;i<size/2;i++)
{
char temp=str[i];
str[i]=str[size-i-1];
str[size-i-1]=temp;
}
cout<<str;
}
int main ()
{
string a="abcd";
f(a); //output: dcba
}
I am new to programming so i don't know concepts like pointers which i am guessing is the problem here.
This is because the variable a is not modified by the function void f(string str). f takes a copy of the string and then uses that copy to reverse the string. This means that the original string a is unchanged.
If you want to make it so that f does not take a copy, you can pass the string by reference using the & operator.
void f(string& str) will use the same string for a and str as they will be referring to the same data in memory.
Related
While I am passing an string to a void function(string s="nayem"; f(s);) whose argument is a character pointer its't working.Again I'm passing f("Nayem") it wroks,atleast compilation is ok,why this?
#include<bits/stdc++.h>
using namespace std;
void f(char* p)
{
cout<<p<<endl;
}
int main()
{
string s="NAYEM";
f(s);//not working
//but f("nayem"); this compiles
cout<<s<<endl;
return 0;
}
I am new to c++ & don't know the basics all that well. pls help (sorry if the solution to this is already available, but I couldn't find any)
This is the Error I am getting:
expected primary-expression before ‘]’ token
char CusName[50]=x[];
^
For this code below:
#include <iostream>
using namespace std;
class BankAccount
{
private:
char CusName[50];
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(char x[], char n)
{
char CusName[50]=x[];
}
};
int main()
{
BankAccount customer1;
char cus1Name[50];
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
Your char array looks like a string. Try using std::string instead and prefer using const references for function parameters.
If you want to use char arrays, and if your point was to copy a null-terminated string by value, then use functions like strncpy.
Using std::string may be easier for you to hide the burden of memory allocation and discover the language step by step.
You can instead use string to input and pass values.
#include <iostream>
using namespace std;
class BankAccount
{
private:
string CusName; //CusName of type string
char CusId[10];
float accBalance, dep, witd;
public:
void setCusDetails(string str, char n) //parameter str of type string
{
CusName=str; //Assign it to the already declared 'CusName' variable.
}
};
int main()
{
BankAccount customer1;
string cus1Name;
cin>>cus1Name;
customer1.setCusDetails(cus1Name, 50);
return 0;
}
This question already has answers here:
C++ Adding String Literal to Char Literal
(8 answers)
Closed 3 years ago.
I am new to c++ templates. I am having trouble converting a templated member object to std::string. My code below fails to print the character 'c' (on my machine it prints 'R' instead) and I can't find a way to make it work. Is there a way to do this when using char as type T?
#include <iostream>
#include <string>
template<class T>
class A {
public:
T t;
A(T t1):t{t1}{};
std::string toString(){
return "" + static_cast<char>(t);
};
};
using namespace std;
int main()
{
A<char> a{'c'};
cout << a.toString() <<"\n";
return 0;
}
The problem with
return "" + static_cast<char>(t);
is that "" isn't a std::string object, it's a literal string which is a constant array of characters. As an array it will decay to a pointer to its first element, and you add static_cast<char>(t) to the pointer.
This new pointer will then be used as a null-terminated string to create a std::string object, and that usage of the invalid pointer leads to undefined behavior.
You can construct a std::string directly from a single character and return it as
return std::string(1, static_cast<char>(t));
Change
return "" + static_cast<char>(t);
to
return std::string() + static_cast<char>(t);
With the original, you have a string literal treated as a pointer.
If std::string is constructible from T you can use the following solution:
#include <iostream>
#include <string>
template<class T>
class A {
public:
T t;
A(T t1):t{t1}{};
std::string toString(){
return {t}; // <- this constructs a string from t
};
};
using namespace std;
int main()
{
A<char> a{'c'};
cout << a.toString() <<"\n";
return 0;
}
Live code here.
However this will fail if std::string is not constructible from T. In that case you can use template specialisation to handle the conversion properly.
I can't figure out why this won't work?
I need to pass the vector reference so I can manipulate it from an external function.
There are several questions on this on the internet but I can't understand the replies?
code below:.
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string funct(vector<string> *vec)
{
cout << vec[1] << endl;
}
int main()
{
vector<string> v;
v.push_back("one");
v.push_back("two");
v.push_back("three");
}
Firstly you need to learn the differences between references and pointers and then the difference between pass-by-reference and pass-by-pointer.
A function prototype of the form:
void example(int *); //This is pass-by-pointer
expects a function call of the type:
int a; //The variable a
example(&a); //Passing the address of the variable
Whereas, a prototype of the form:
void example(int &); //This is pass-by-reference
expects a function call of the type:
int a; //The variable a
example(a);
Using the same logic, if you wish to pass the vector by reference, use the following:
void funct(vector<string> &vec) //Function declaration and definition
{
//do something
}
int main()
{
vector<string> v;
funct(v); //Function call
}
EDIT: A link to a basic explanation regarding pointers and references:
https://www.dgp.toronto.edu/~patrick/csc418/wi2004/notes/PointersVsRef.pdf
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.