Is there a way to do something like this :
void test(char *userInput){
//code
}
char userInput = "test";
test(userInput);
I have the error : Process finished with exit code 139 so how can i proceed ?
Is there a way to do something like this :
Sure, just change your code a bit:
void test(const char *userInput){
//code
}
int main() {
const char* userInput = "test";
test(userInput);
}
I have the error : Process finished with exit code 139 so how can i proceed?
I'm pretty sure the compiler did show you some further errors before this one came up. Fix these first.
You marked this as a C++ question ... std::strings are very easy to use.
// NOTE: userinput can be either std::string OR const char*
void test(std::string userinput)
{
// code, perhaps echo testing input
std::cout << userinput << std::endl;
}
// test 290 - invoked somewhere in main
int t290(void)
{
std::string userInput = "test1";
test(userInput);
// some times you can save some typing
test("test2"); // function declared as above
// accepts both const char* or std::string
return (0);
}
As other people pointed out, there's an error in your code, char should be changed to const char*. Char only holds one value, not the entire string, and if your function takes a const value the string has also to be. Also, given you're using C++, you can use std::string wich is really straightforward to use.
Related
human header
class human
{
char name[];
public:
void setName(char nameValue[]);
char* getName();
}
human cpp
void human::setName(char nameValue[])
{
char name[] = "walter";
}
char* human::getName()
{
return name;
}
main cpp
int main()
{
human myHuman;
char name[] = "walter";
myHuman.setName(name);
char* result3 = myHuman.getName();
cout << "My human has a name of " << result3 << endl;
return 0;
}
I assign the string "walter" but when I print it I get "╠╠╠╠╦ß╩d└²╒".
I don't understand which part is wrong. Can you tell me what's wrong with my code?
First and foremost you are assigning nameValue to a variable local to the function setName, which means that the class variable name is still unitialized when you return it in getName, hence the strange output.
The char name[]; declaration is also incorrect, C++ does not allow for variable length arrays or arrays with unspecified bounds unless they are immediately initialized in which case the size will be deduced given the size of the assigned string.
On that note, warnings must have been issued by your compiler, if not, crank them up, or better yet, make it treat warnings as errors, you'll have more robust code.
For the purpose of your assignment you should just go ahead and use pointers, a small problem arises because C++ does not allow for assignment of string literals to char* variables, this is easily fixed if you use const char*, your compiler may allow the former but it is illegal as per C++ rules.
Applying the corrections above, your code should look more like this:
class human
{
const char* name;
public:
void setName(const char *nameValue);
const char* getName();
};
void human::setName(const char *nameValue)
{
name = nameValue;
}
const char* human::getName(){
return name;
}
int main()
{
human myHuman;
const char* name = "walter";
myHuman.setName(name);
const char* result3 = myHuman.getName();
cout << "My human has a name of " << result3 << endl;
return EXIT_SUCCESS;
}
I would like to be able to do the following:
std::cout << str_manip("string to manipulate");
as well as
std::string str;
str_manip(str);
std::cout << str;
For this, I have two functions
#include <string>
// copying
std::string str_manip(std::string str)
{
// manipulate str
return str;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
but they produce the following error:
error: call of overloaded 'str_manip(std::__cxx11::string&)' is ambiguous
How can I overcome this?
The problem is with this call:
std::string str;
str_manip(str);
std::cout << str;
The compiler doesn't know which version of str_manip to call.
You can change your functions to look like this:
#include <string>
// copying
std::string str_manip(const std::string& str)
{
std::string dup = str;
// manipulate dup
return dup;
}
// in-place
void str_manip(std::string& str)
{
// manipulate str
}
Now, the compiler knows that the ambiguous call has to be the function that takes the non-const parameter. You can also be sure that your call that returns a std::string to the << operator isn't modifying your string.
This might be not the thing you are looking for, but for your code
std::cout << str_manip("string to manipulate");
the parameter to str_manip is not a string but const char* (actually an array, but convertible to a char pointer). You can overload based on that.
std::string str_manip(const char* s)
{
std::string str(s); // create str
// manipulate str
return str;
}
However, let's look at the big picture. When you see str_manip in your code, does this mean "change the string" or "make a new string based on the given string"? Do you want to be intentionally ambivalent on the real meaning?
Consider yourself reading your code in 1 year in future. What will you think when you see a call to str_manip - does this mutate its parameter? Does the answer to the previous question depend on context?
The goal in writing code is to make it clear, especially in a multi-paradigm language like C++. So, in my opinion, just don't do overloading that you are thinking about. Instead, make 2 distinct names, like
void frobnicate_str(std::string&) {...}
std::string get_frobnicated_str(std::string) {...}
I have this code that works as expected:
#define MAX_PARAM_NAME_LEN 32
const char* GetName()
{
return "Test text";
}
int main()
{
char name[MAX_PARAM_NAME_LEN];
strcpy(name, GetName());
cout << "result: " << name << endl;
}
If I'd like to store the result to a char * (because some functions within a Frameworks I'm using use only char * as input) without using the strcpy (for practicality and readability of code, and learning too), how could I do? Keeping in const, this works well:
const char* name;
name = GetName();
but I still have const.
Trying to just use char*:
char* name;
name = GetName();
I get invalid conversion from 'const char*' to 'char*'. What's the best habit for this kind of conversion?
The best habit for this kind of conversion is to use std::string throughout your code. Since the framework that you are using takes const char* as its input, you can always pass it the results of c_str() call on your std::string:
std::string GetName() {
return "Test text";
}
int main() {
std::string name = GetName();
int res = external_framework_function(name.c_str());
cout << "result: " << res << " for " << name << endl;
}
A distant second best is using const char* in your code:
const char* name = GetName();
Since the framework that you are using takes const char* you are good here as well.
If you need a non-const pointer, there is no way around copying the string. You can make a function that does it for you, but you would remain responsible for freeing the copies that you get from it:
char* copy(const char* orig) {
char *res = new char[strlen(orig)+1];
strcpy(res, orig);
return res;
}
...
char *name = copy(GetName());
...
delete[] name;
return "Test text"; returns a pointer to a read-only string literal.
If you're using a function that takes a char* as an input, and you have a const char* (such as a read-only string literal), then you ought to supply a deep copy of the string starting at that const char* to such functions.
Else you risk undefined behaviour at runtime if a function attempts to modify a read-only string.
What you currently have is adequate; assuming you can't work with std::string. (If you can work with std::string and all your framework functions take a const char* input, then I'd suggest your refactoring your code to use a std::string, and pass the output of the c_str() method on that string class to your framework functions.)
Finally, if some of your framework functions require a char* then you could always build yourself a small adapter class:
class Adapter
{
public:
Adapter(const& Adapter) = delete; /*don't try to copy me please*/
Adapter& operator=(const Adapter& ) = delete; /*don't try to copy me please*/
Adapter(const char* s) : m_s(::strdup(s))
{
}
~Adapter() /*free memory on destruction*/
{
::free(m_s); /*use free to release strdup memory*/
}
operator char*() /*implicit cast to char* */
{
return m_s;
}
private:
char* m_s;
};
Then for a function void foo(char* c), you can call foo(Adapter("Hello"/*or any const char* */)); and foo can do as it pleases with the char* that's embedded in the anonymous temporary! You could even enhance this class to take a constructor to a char* where in that case only a shallow copy of the pointer is taken (and the destructor doesn't delete the memory).
In C++, the typical way to "drop const" is by using const_cast<>:
char *name = const_cast<char*>(GetName());
This is, of course, frowned upon, ugly and potentially dangerous, since it's really possible that GetName() returns a pointer to something that shouldn't be changed, and then you go and give yourself permission to change it. It's a good way to get very hard to find bugs, in that case.
A workaround is to use a std::string as a temporary holding area; it will mean copying the string but that might be acceptable performance-wise:
std::string s(GetName());
char *name = s.c_str();
This will of course only work if name isn't kept around when s goes out of scope. If that is the case, then you're going to have some form of persistent string storage layer.
You could explicitly cast it. (char*) getName(). But you probably shouldn't. Because the const bit means something like "promise not to change it". So if i have a function void foo(const char* string) I am saiying: "give me a pointer to a string. I won't change it."
And if you declare a variable const char* string = "hello"; You are saying, this string should not be changed. And because you make this promise, the compiler knows, and can make your code more efficient. This is why:
const char* a = "hello";
const char* b = "hello";
(a==b); //is probably true
your compiler knows you won't change a or b so it makes them point to the same address, so it only has to store one "hello" string. If you now go about changing a, b gets also changed, and this is not what you wanted.
So long story short, if you are absolutely sure that the function your calling does not change the string, you can explicitly cast it. (or better, change the function to (const char*) if it's yours).
If your not sure, you will have to make a copy. (Like you are already doing with strcpy()).
I'm writing a program where I create my own string class. The program is supposed to instruct the user to write a sentence, copy the input, and then display how many characters it contains.
Although it did build and compile (using Visual Studio Express 2013), it would copy the sentence the user is instructed to write down, not display the amount of characters, and then crash.
I'm guessing is has something to do with how the memory is dynamically allocated or how *character and _String is passed between functions. But some help on how to fix this or improve my code would be very helpful.
Header: String.h
class String
{
private:
char *characters[50]; // 50 is just a placeholder to get it to work
int size;
public:
// Constructors and Destructors
String();
String(char*);
~String();
// Other functions
void stringAssign(char*);
void printString(char*);
int stringSize(char*) const;
};
Implementation: String.ccp
#include "String.h"
#include <iostream>
#include <cstring>
String::String()
{
size = 0;
* characters = 0;
}
String::String(char* _String)
{
size = stringSize(*characters + 1);
_String = new char[size];
}
String::~String()
{
delete [] *characters;
}
void String::stringAssign(char* _String)
{
_String = characters[size];
}
void String::printString(char* _String)
{
for (int i = 0; _String[i] != '\0'; i++)
std::cout << _String[i];
}
int String::stringSize(char* _String) const
{
int size;
size = strlen(*characters);
return size;
}
Test: Main.ccp
#include "String.h"
#include <iostream>
int main()
{
char string[50];
String s;
std::cout << "Enter a sentence that is less than 50 characters\n\n";
std::cin.getline(string, 50);
s.printString(string);
std::cout << s.stringSize(string);
return 0;
}
Solved:
I got the program working. Literally all I did was replace the two *character arguments with _String in the implementation. I knew it had something to do with function passing, and I did get a little help for that. But one person gave no helpful input (and practically insulted me) and both said that there were "too many things to fix". Some elaboration on the "so many things" I had to fix would be nice.
In almost all functions, you do something with the argument of the function, _String, and not with the member field characters that is supposed to hold the string internally. So your functions do not change the string at all, but rather try to mess with something you passed them.
An example
struct Foo {
char internal[42];
void bar(char *external) { external[0] = 'X'; }
void qux(char *external) { internal[0] = 'Z'; }
};
int main() {
Foo foo;
char something[6] = "Hello";
foo.qux(something); // Did something to the member variable foo.internal; variable something is unchanged.
foo.bar(something); // Now something reads "Xello", foo.internal was not changed.
}
Your code does almost as the function bar while it should work like qux.
There is indeed too much to fix in this code.
Just in case you were mistaken... Unlike some other languages, say Python or Smalltalk, C++ passes a pointer to the current object implicitly via this.
I was wondering whether there is a way in C++ that a "string" (in whatever representation) that get's passed into a function can be assumed to be a valid string by that function.
I'm very new to C/C++ but so far as I can see, in C that question is answered by default because there is no other way und you just know that you have to check:
#include <stdio.h>
void foo(const char *str)
{
if (str)
printf("%s\n", str);
}
int main()
{
char *name = "Jack";
foo(name);
return 0;
}
But since C++ offers additional stuff like references I was wondering whether one could write foo() in such a way that it doesn't have to check. I tried it like this:
#include <iostream>
#include <string>
void foo(const std::string &str)
{
std::cout << str << std::endl;
}
int main(void)
{
std::string name = "Jack";
foo(name);
std::string *str = NULL;
foo(*str);
return 0;
}
But as you can see I can fool foo() to run into a SegFault. So, I guess you just always have to check, no matter what?
EDIT #1:
Okay, first of all thanks for all your answers and future answers, they are all much appreciated!
So to sum up what I learned so far:
There is no syntactic way in C++ to write a function defintion to
eliminate misuse by the actual function call.
Is that correct? If so, I see my original question as answered.
So now I trying to write foo() as defensive as possible, so that no matter how much you treat foo() like a dog, it just won't produce a SegFault.
In C I would now write it like this (assuming short-circut evaluation):
#include <stdio.h>
void foo(const char *str, const size_t len)
{
if (str && (str[len - 1] == '\0'))
printf("%s\n", str);
}
int main()
{
char *name = "Jack";
foo(name, 5);
/* possible mistakes, but foo can handle them */
foo(name, 4);
foo(name, -1);
foo(NULL, 5);
return 0;
}
And in C++ I'm trying this:
#include <iostream>
#include <string>
void foo(const std::string &str)
{
if (&str)
std::cout << str << std::endl;
}
int main(void)
{
std::string name = "Jack";
foo(name);
std::string *str = NULL;
foo(*str);
return 0;
}
...but I'm not sure if that is in any approriate or what one would, could or should do with exceptions in this case.
What do you think? If you can't prevent misuse by syntax you gotta increase the precautions?
std::string *str = NULL;
foo(*str);
This is undefined behavior, on the part of the caller. Not your problem. So no, you(the writer of foo) don't have to check.
Even in C, with the pointer, you don't necessarily have to check. You just have to document. "The argument must point to a valid null-terminated string. If it is not, the call is undefined behavior." -- If the user passes a NULL, that is, again, their problem. This is done all the time. If it wasn't, you'd have wasteful call chains checking the validity of the pointer at every level like this:
void foo(const char * s)
{
if (s)
printf("%s", s);
}
void bar(const char * s)
{
if (s)
foo(s);
}
void baz(const char * s)
{
if (s)
bar(s);
}
No, you're not right.
In the second code, undefined behaviour happens when you dereference your pointer, before you ever get to your function.
This is not a problem of your function. Inside your function, with the second signature you can always assume that you have a valid string, which makes it superior to the first one.