#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?
Related
I am having an issue receiving this error when compiling code similar to the below.
I am getting this error: invalid conversion from 'const char*' to 'char*' [-fpermissive].
I am unsure why as the strchr function accepts const char* ? maybe I am confused here. I have looked at other people having this same error on this site but I still don't see the solution clearly.
People had mentioned UNION? I have no clue how to use this keyword and was wondering if I could get clarification.
Could someone explain why this is happening or how is the safest/best method to resolving this error? I have other errors just like this in other spots in my code in the same situation.
#include <strings.h>
#include <cstring>
#include <string>
#include <stdio.h>
int main()
{
validURL ('www.why_CPP_hates_me.com');
return 0;
}
bool validURL (const char *url)
{
char *q = strchr (url, '?');
...
return true;
}
The right way to this is:
#include <cstring>
#include <string>
#include <stdio.h>
bool validURL(const char *url); // Must forward declare or prototype the
// function before calling
int main()
{
validURL("www.why_CPP_hates_me.com"); // Single quotes are for single chars
// Double quotes are for string
// literals, which create a const char*
return 0;
}
bool validURL(const char *url)
{
const char *q = strchr(url, '?'); // You have to assign to a const char*
// to maintain const correctness.
// strchr() has const char* and char*
// overloads. But you have to assign to
// the correct type.
return true;
}
Or if you wanted to you could do this:
bool validURL(const char *url)
{
char *q = strchr(const_cast<char*>(url), '?');
// Casting away const is not recommended generally. Should be careful.
return true;
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I want to make a custom String class for C++. But when I do this:
g++ test.cpp sys/Base.h sys/Base.cpp
I get this error:
sys/Base.cpp: In function 'const char* Base::toChar()':
sys/Base.cpp:57:13: error: 'strval' was not declared in this scope
return strval;
^
sys/Base.cpp: In function 'std::string Base::toStr()':
sys/Base.cpp:60:20: error: 'strval' was not declared in this scope
return string(strval);
^
test.cpp
#include "sys/Base.h"
int main() {
Base::write("Hello there.\n");
return 0;
}
sys/Base.h
// Header file handling
#ifndef ARAVK_BASE_H
#define ARAVK_BASE_H
// Includes
#include <string>
// Global variables
#define EXIT_YAY 0
#define EXIT_ERR 1
using namespace std;
namespace Base {
// Classes:
class String {
static const char* strval;
public:
// Constructors:
String();
String(char[]);
String(const char*);
String(string);
// Destructors:
~String();
// Operators:
// =
void operator=(const String&);
void operator=(const char*&);
void operator=(const string&);
// Conversion:
const char* toChar() const;
string toStr() const;
};
// Functions:
// Input-Output:
// Write:
void write(String);
void write(string);
void write(const char*);
// Read:
String read();
// Executing:
String run(String);
}
#endif
sys/Base.cpp
// Including
#include "Base.h"
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
// Global variables
#define EXIT_ERR 1
#define EXIT_YAY 0
/* ------------------------ */
using namespace std;
namespace Base {
// Classes
// String functions
// Constructors
String::String() {
const char* strval = "";
}
String::String(const char* str) {
const char* strval = str;
}
String::String(string str) {
const char* strval = str.c_str();
}
String::String(char str[]) {
const char* strval = str;
}
// Destructors
String::~String() {
delete strval;
}
// Operators
// =
void String::operator=(const String &strp) {
strval = strp.toChar();
}
void String::operator=(const char* &strp) {
strval = strp;
}
void String::operator=(const string &strp) {
strval = strp.c_str();
}
// Conversion:
const char* toChar() {
return strval;
}
string toStr() {
return string(strval);
}
// Functions:
// Input-Output:
// Write
void write(String str) { printf(str.toChar()); }
void write(const char* str) { printf(str); }
void write(string str) { printf(str.c_str()); }
// Read
String read() { char str[100]; scanf("%s", str); return String(str); }
//TODO: More to come
// Executing
/*String run(String command) {
const char* cmd = command.toChar();
char buffer[128];
string result = "";
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw runtime_error("popen() failed!");
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL)
result += buffer;
}
return String(result);
}*/
String run(String command) {
char buffer[128];
std::string result = "";
const char* cmd = command.toChar();
FILE* pipe = popen(cmd, "r");
if (!pipe) throw std::runtime_error("popen() failed!");
try {
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
} catch (...) {
pclose(pipe);
throw;
}
pclose(pipe);
return String(result);
}
}
I'm not sure why this is happening. I think it's related to how I've declared/defined the const char* 'strval'. Can anybody help?
P.S: If the answer is too big, this project is on Github: AravK/C-Applications
Let's take a look at your constructor:
String::String() {
const char* strval = "";
}
This declares a local variable called strval. The variable is local to the constructor; it doesn't exist once execution of the constructor completes.
What you need instead is a member variable - declare it inside the class, but not inside a member method or constructor. In fact, you have already defined it as such in the header file:
class String {
static const char* strval;
So, remove the const char * from your constructor and add a class qualifier, so that the line becomes an assignment to the existing variable, rather than creation of a local:
String::String() {
String::strval = "";
}
And also change the return statement that is giving you the error:
return String::strval;
Or perhaps - and this is likely what you really wanted - remove the static qualifier from the variable definition, and change the constructor instead to just:
String::String() {
strval = "";
}
Furthermore, your destructor incorrectly deletes data that was not necessarily dynamically allocated, or which may belong to another object:
String::~String() {
delete strval;
}
This requires re-working. At the moment the simplest solution is to remove the delete strval altogether.
Your read() function potentially instigates a buffer overflow, by using scanf("%s") with a fixed size buffer and unknown input size:
char str[100]; scanf("%s", str); return String(str);
Finally, your command line:
g++ test.cpp sys/Base.h sys/Base.cpp
... should not include the header file (Base.h). You are specifying the units you want compiled, and Base.h is already included in Base.cpp; it is not a standalone unit that should be compiled invidually.
yes you did not define the variable in your class as a field.
there is 3 locals déclaration in your constructors.
just add it the way you have done in the header.
static const char* strval
and remove the définition in your constructors. Just keep the assignement part.
regards
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]);
Hi I am new in c++ and I make skeleton of program and I have some problems with destructors and constructors.
My head.cpp:
#include <iostream>
#include "set_char.hpp"
using namespace std;
int main()
{
set_char *z1 = new set_char(unsigned char *zbior[]);
delete z1;
return 0;
};
My set_char.hpp class file:
#define ROZMIAR_MAX 256
class set_char
{
unsigned char zbior[ROZMIAR_MAX];
public:
set_char(unsigned char *zbior[]);
~set_char(unsigned char *zbior[]);
int nalezy(unsigned char);
int licznosc();
void dodaj(unsigned char);
void usun(unsigned char);
};
And my set_char.cpp file:
#include "set_char.hpp"
#include <iostream>
#include <math.h>
using namespace std;
set_char(unsigned char *zbior[]);
~set_char(unsigned char *zbior[]);
void set_char::dodaj(unsigned char)
{
};
void set_char::usun(unsigned char)
{
};
int set_char::nalezy(unsigned char)
{
};
int set_char::licznosc()
{
};
Among others:
you should not add any parameters in destructors:
~set_char(unsigned char *zbior[]);
^^^^^^^^^^^^^^^^^^^^^^ --- remove it
When creating set_char you should provide pointer to your array, and not the actual parameter type:
set_char *z1 = new set_char(unsigned char *zbior[]);
^^^^^^^^^^^^^^^^^^^^^^
1
You did not define your Constructor and Destructor
You declared them both in your set_char.hpp
set_char(unsigned char *zbior[]);
~set_char(unsigned char *zbior[]);
However in set_char.cpp you re-declare them again without a return type. Defining a Constructor and Destructor outside of a class is illegal. Your compiler thinks they are functions and searches for a return type.
2
a Destructor may not have any arguments.
3
If you define an array as an argument in a Function or a Constructor or Destructor with brackets '[]', it may not be of variable length, thus it must be defined. If it is intended to be of variable length, it must be left out.
4
You are calling the constructor in a bad way using:
new set_char(unsigned char *zbior[]);
You already declared what arguments it takes, so hand it the arguments. A null pointer, for example.
The correct way to do it in set_char.hpp:
set_char(unsigned char *);
~set_char();
The correct way to do it in set_char.cpp:
set_char::set_char(unsigned char *zbior)
{
//Your definition
}
set_char::~set_char();
{
//Your definition
}
The correct way to do it in head.cpp:
set_char *z1 = new set_char(0x0);
Also side-note, usually using the define macro to define constants, is a C way. In C++ it is usually done with:
static const size_t ROZMIAR_MAX 256;
Second side-note. It is considered 'neater' code if you have your constants/functions and whatnot defined inside a namespace
Consider the following constructor of a class i C++. It gives me the error :
default argument for parameter of type ‘char’ has type ‘const char [2]’
Some advices please. I would be happy if I could set the default constructor for correctAnswer at "" (nothing).
#include <string>
#include <iostream>
class Question{
int id;
std::string text;
char correctAnswer;
public:
Question(int id=0, const std::string& text="", char correctAnswer="a") : // here is the error
id(id),text(text),correctAnswer(correctAnswer) {
}
}
Change it to
Question(int id=0, const std::string& text="",char correctAnswer='a')
'a' is a single char.
Double quotes always creates an array.
"Hello" is an array of size 6.
"a" is an array of size 2.
The extra 1 is for a null terminator (0 or '\0')
Question(int id=0, const std::string& text="",
char correctAnswer='a')
// ^^ Use single Quote for a char
id(id),text(text),correctAnswer(correctAnswer)
{
}