type casting of strings - c++

I am trying this simple piece of code to accept a string in one function and pass it to other function
#include <iostream>
#include <string>
using namespace std;
void set_name(char *deviceName)
{
cout<<"Local Device name is:"<<endl;
cout<<deviceName<<endl;
}
void enter_name()
{
cout<<"Enter a user friendly name"<<endl;
string name;
getline(cin, name);
cout << "Entered name is:"<<endl;
cout << name<<endl;
set_name(name);
}
int main()
{
enter_name();
return 0;
}
but when I compile this code I am getting the following errors:
error C2664: 'set_name' : cannot convert parameter 1 from 'std::string' to 'char *'
somebody please help me to sort out this error, make sure I don't want to change the prototype of set_name();

Your function set_name is taking a char* parameter, whereas you are attempting to pass a std::string. If your function parameter was a const char*, it would implicitly convert for you:
void set_name(const char* name);
std::string name = "MyName";
set_name(name);
However, you are telling the compiler that this char* is allowed to be modified because it isn't const, and a std::string and string literal (strings within double-quotes) cannot be modified.
As your function does not change deviceName, it makes the most sense to make your parameter a const char*; however, it makes even more sense for it to be a std::string!
void set_name(const std::string& deviceName)
{
cout<<"Local Device name is:"<<endl;
cout<<deviceName<<endl;
}
Which can be called like:
// string literal
set_name("MyDeviceName");
const std::string device = "MyDeviceName";
// string
set_name(device);
// char*
char* device = "MyDeviceName"
set_name(device);
BUT, if you truly have reasons to pass a char* and don't intend to modify the parameter, you can call it like so:
string name;
...
set_name(&name[0]);

Related

Can't pass full array value to another function in C++

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;
}

Cannot Convert 'char (*)[200]' to 'char**'

#include <iostream>
#include <string.h>
using namespace std;
void ArrayTimesThree(char*, const char*);
int main()
{
char s1[200], s2[200], circleword[200];
cin.getline(s1, 200);
cin.getline(s2, 200);
ArrayTimesThree(circleword, s1);
cout<<circleword[1];
}
void ArrayTimesThree(char *dest[], char *source[])
{
*dest[0] = NULL;
strcat(*dest, *source);
strcat(*dest, *source);
strcat(*dest, *source);
}
main.cpp|21|error: cannot convert 'char (*)[200]' to 'char**' for argument '1' to 'void ArrayTimesThree(char**, char**)'
You're passing ArrayTimesThree a char*, however, in the method signature you're telling it to expect a char**. Don't forget that that using the [] operator counts as a dereference. Try this:
#include <iostream>
#include <string.h>
using namespace std;
void ArrayTimesThree(char*, char*);
int main()
{
char s1[200], s2[200], circleword[200];
cin.getline(s1, 200);
cin.getline(s2, 200);
ArrayTimesThree(circleword, s1);
cout<<circleword[1];
return 0;
}
void ArrayTimesThree(char *dest, char source[])
{
dest[0] = '\0';
strcat(dest, source);
strcat(dest, source);
strcat(dest, source);
}
Disclaimer: I'm not sure what exactly you're expecting out of this code, so I cannot guarantee the logic is correct; however, this will take care of your compiler errors and seems to function correctly for how the code is written.
The problem is really just because your initial declaration of ArrayTimesThree (which is the 'correct' one) doesn't match the definition you later give (which is wrong, in fact). Change your definition as below and it works:
void ArrayTimesThree(char* dest, const char* source) // Needs to be the same as in the previous declaration!
{
dest[0] = '\0'; // Don't assign a string pointer to NULL! Instead, set its first character to the nul character
// strcpy(dest, ""); // ALternatively, use strcpy with an empty string to clear "dest"
strcat(dest, source); // strcat takes char* and const char* arguments ...
strcat(dest, source); // ... so there is no need to 'deference the values ...
strcat(dest, source); // ... now that the argument types have been 'corrected'
}
Incidentally, I notice that the input value for s2 in your main function is never actually used … is this what you intend, for now?

Why is my Code runing under codeblocks but not in VS Studio

This line canot pass under VS Studio, But it is running under CodeBlocks.
cg1.RegisterGoods("c++", 23, 32);
'void CGoods::RegisterGoods(char [],int,float)': cannot convert argument 1 from 'const char [4]' to 'char []'
like so:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include <cstring>
using namespace std;
class CGoods
{
private:
char Name[21];
int Amount;
float Price;
float Total_value;
public:
void RegisterGoods(char name[], int amount, float price)
{
strcpy(Name,name);
Amount = amount;
Price = price;
}
void CountTotal(void)
{
Total_value = Price * Amount;
}
void GetName(char name[])
{
strcpy(name,Name);
}
int GetMount(void)
{
return Amount;
}
float GetPrice(void)
{
return Price;
}
float GetTotal(void)
{
return Total_value;
}
};
int main() {
CGoods cg1;
cg1.RegisterGoods("c++", 23, 32);
cout<<cg1.GetPrice()<<endl;
cout<<cg1.GetMount();
return 0;
}
char name[] as a function parameter is equivalent to char *name while your string literal has a type const char [4] which can only be (safely) converted to const char *, so you have to change your parameter like this:
void RegisterGoods(const char *name, int amount, float price)
and here:
// Renamed to SetName given that it's what this function actually does
void SetName(const char *name)
In general though you shouldn't use plain char arrays to store strings in C++, you should instead prefer using std::string:
std::string Name;
...
void SetName(std::string name)
{
// take advantage of move semantics to avoid redundant copying
// if you are using C++11 and beyond
Name = std::move(name);
}
Don't use c-constructs for things, c++ has better answers. char-pointers can lead to unwanted behaviors and nasty buffer overflow exploits and so on. It is far better to use a std::string.
Change your member-function RegisterGoods to:
void RegisterGoods(std::string const & name, int const amount, float const price)
{
Name = name;
Amount = amount;
Price = price;
}
and your declaration of Nameto:
private:
std::string Name;
your return function GetName to:
std::string GetName() const
{
return Name;
}
OR
void GetName(std::string & name) const
{
name = Name;
}
also add the include for std::string:
#include <string>
Tip for a better code... don't use using namespace std. std is a enormously huge namespace. Unintentionally you may override a function out of std and you end up with a nearly undebuggable error.
Also define your parameters in setter functions as const, so you can't change the value of it unintentionally.
Is that means that we don't need strcpy and char in c++ anymore? Because i replaced all the 'char' with string and its funktion also. like this:
private:
std::string Name;
public:
void RegisterGoods(const string name, int amount, float price)
{
Name=name;
Amount = amount;
Price = price;
}
const std::string GetName()
{
return Name;
}

No matching constructor for initialization of

I’ve seen similar questions on StackOverflow, but none of them seems to apply to me.
Here is my code:
Option.cpp
#include "Option.h"
Option::Option(string valueName, string description, OptionType type){
this->valueName = valueName;
this->description = description;
this->type = type;
};
Option.h
#include <iostream>
using namespace std;
enum OptionType { FLAG, REQUIRED, NORMAL };
class Option {
string valueName, description, value;
OptionType type;
public:
Option(string valueName, string description, OptionType type);
void setValue(string value) {
this->value = value;
};
string getValueName() {
return this->valueName;
};
string getDescription() {
return this->description;
};
OptionType getType() {
return this->type;
};
};
Options.cpp
#include "Options.h"
using namespace std;
Options::Options(int _argc, const char * _argv[]) : argv(_argv) {
this->argc = _argc;
}
Options::~Options() {
options.~unordered_map();
}
void Options::printHelp() {
for (auto &i : options) {
cout << i.first << '\t' << i.second.getDescription() << '\n';
}
}
void Options::addFlag(string flagName, string description) {
}
void Options::addOption(string optionName, string valueName, string description, OptionType type) {
Option option(valueName, description, type);
options[optionName]=option;
}
void Options::addOptionAlias(string aliasName, string optionName) {
}
Options.h
#include <iostream>
#include <unordered_map>
#include "Option.h"
using namespace std;
class Options {
unordered_map<string, Option> options;
int argc;
const char ** argv;
public:
Options(int argc, const char * argv[]);
~Options();
void parse();
void addOption(string optionName, string valueName, string description, OptionType type);
void addFlag(string flagName, string description);
void addOptionAlias(string aliasName, string optionName);
void getOption(string optionName);
void printHelp();
};
It's in options.cpp on the line Option option(valueName, description, type); that the error seems to stem from, but for the life of me, I can’t figure out why. As far as I can see, the constructor in Option takes the right types.
The problem is actually in the next line:
options[optionName]=option;
That first calls the operator[] in the map, that searchs for the given key and returns the associated value. If the key is not found, it insert a default initialized value connected to that key. Then this value is copy assigned with your option.
Do you see the problem? Your Option class does not have a default constructor, so it cannot be default initialized! Read carefully your error message, surely it is talking about the default constructor, not the one you are looking at.
You have several solutions. The easiest would be to write a default constructor for your class.
The alternative would be never to use operator[] in the map so that the default constructor is never needed. If that's what you want to do, to insert an item you write:
options.insert(std::make_pair(optionName, option));
Finally, if you are using C++11 (or later) and a compliant enough compiler, you can even build the object directly into the container: zero copy overhead and you don't even need the copy constructor!
options.emplace(std::piecewise_construct,
std::forward_as_tuple(optionName),
std::forward_as_tuple(valueName, description, type));
There's a mismatch between the declaration of the constructor in the header and the definition in the source file.
In header...
Option(string& valueName, string& description, OptionType& type);
In source file...
Option::Option(string valueName, string description, OptionType type){
Notice the parameters are defined as references (e.g., string&) in the header, but as objects (e.g., string) in the source.

error: incompatible types in assignment of ‘char’ to ‘char [11]’

I'm trying to create a member function that allows an user to set member array variables.
I've been looking everywhere but I can't find the problem in my code,
#include <string>
#include <iostream>
using namespace std;
class Employee
{
protected:
string name;
char ssn[11];
char id[5];
char hired[8];
public:
Employee(char ssn, char id, char hired); //Constructor
Employee(string name);
~Employee(); //Destructor
void setName(string n) { n = name; }
void setSSN(char i) { ssn = i; }
};
int main()
{
return 0;
}
Let's have a look at your setSSN function:
void setSSN(char i) { ssn = i; }
SNN, which most likely means social security number, doesn't consist of just one digit but 11, right? Then why would setSSN take as input only one character (digit) by (char i)? So setSSN function should rather take a string of characters containing SSN of the employee and that string should be of the same flavor as the ssn member variable of your Employee class in order to let you assign one string variable by another in the body of setSSN function. If you are already familiar with the string class of the C++ standard library, you should probably use that class for all your string storage and manipulation.