How to pass a String without quotes to function? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
template<typename... Args>
void callJavaScript(const Args&... args) {
// TO-DO
}
callJavaScript({
console.log("Hello World")
})
Is it possible to accomplish something like this with Variadic templates (with/without Macro hack)?
Instead
callJavaScript("{
console.log('Hello World')
}")
I want
callJavaScript({
console.log("Hello World")
})
Here an example I found that use Macros,
#define MULTI_LINE_STRING(a) #a
const char *text = MULTI_LINE_STRING(
Using this trick(,) you don't need to use quotes.
Though newlines and multiple white spaces
will be replaced by a single whitespace.
);
Here is my version of this macro,
#define createScript(name, ...) \
const char *name = #__VA_ARGS__;

Answering my own question.
void callJavaScript(std::string script) {
std::cout << script << "\n";
}
#define callJavaScript(...) callJavaScript(#__VA_ARGS__)
Now you can call like this,
callJavaScript({
console.log("Hello World")
})
You can compile this then it will output
{console.log("Hello World")}
If anyone has a better way with templates, please do tell.

Related

Make each element in a string list lowercase using Kotlin [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the following function:
fun listToLowerCase(names: List<String>) {}
I wish to make the "names" list lowercase in-place something like:
names = names.map { it.lowercase() }
What would be the most efficient way to do it in Kotlin and why?
You cannot modify a List<*> in-place in Kotlin because this type represents read-only lists.
It's more common in Kotlin to use a functional approach for this and return a new List, instead. As you have stated, this can be accomplished with a simple map { it.lowercase() }.
If you really really want to do it in-place, you'll need to work with a MutableList:
fun listToLowerCase(names: MutableList<String>) {
names.replaceAll(String::lowercase)
// or depending on taste:
// names.replaceAll { it.lowercase }
}
Which you can then use like this:
val list = mutableListOf("Bob", "George", "FRED")
listToLowerCase(list) // mutates the list
println(list) // [bob, george, fred]
You wouldn't even really need a helper function for this, to be honest.
The following works. Why overthink the problems?
fun main(args: Array<String>) {
val names = listOf("Name1", "Name2", "Name3")
print(listToLowerCase(names))
}
fun listToLowerCase(names: List<String>): List<String> {
return names.map { it.lowercase() }
}
You can also define an extension:
// An extension function for List<String>:
fun List<String>.lowerCase(): List<String> = this.map { it.lowercase() }
Then you can use it like this:
val lowerCaseList = listOf("Banana", "Pineapple", "Orange").lowerCase()
println(lowerCaseList)
In terms of efficiency, the map approach is very similar to using a for loop. And since it is definitely more redeable and less error prone, you should go with it.

Unable to generate correct char array in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
myFunction(){
char *tempPath = getenv("LocalAppData");
strcat(tempPath, "\\MS\\namedPipe.json");
printf(" the path is %s \n",tempPath
}
int main(){
myFunction();
myFunction();
return 0;
}
I don't know the second time that I call this function I am getting the path to be appended like
Quoting the man page for getenv:
As typically implemented, getenv() returns a pointer to a string within the environment list. The caller must take care not to modify this string, since that would change the environment of the process.
In other words, what you are currently doing is not allowed.
Instead make another buffer and concatenate in that buffer. Eg:
char *tempPath = getenv("LocalAppData");
if (tempPath != NULL)
{
std::string env;
env = tempPath;
env += "\\MS\\namedPipe.json"
std::cout << env;
}
else
{
std::cout << "No such environment variable\n";
}

How to convert a C++ macro to a more elegant solution [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I wrote a C++ macro to wrap the execution of two generic functions:
#define DO_ACTIONS( action1, action2, handle ) \
ResetEvent( handle ); \
action1 \
action2 \
// other common stuff...
Usage examples:
DO_ACTIONS( function1( 1, 2, 3 );,
function2();,
m_handleEvent );
DO_ACTIONS( function1( "some text" );,
function2( -3 );,
m_handleEvent );
I would like to replace this code with something more elegant. Do you think templates can help me with that? Any other idea?
Thanks.
Ordinary templates should suffice for the facility, since there's nothing variadic about your problem:
template <typename F1, typename F2>
void do_actions(F1 f1, F2 f2, handle_type handle)
{
ResetEvent(handle);
f1();
f2();
}
At the call site you could use lambda expressions to generate callable objects:
do_actions([](){ function1(1, 2,3 ); },
[](){ function2(); },
m_handleEvent);
You could also look at std::bind to fix those arguments at setup time.

Remove code which is commented out not actual commments [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
We have a large legacy code base with lots of code which is commented out and is now polluting our source code files. On the other hand we have real comments which I like to preserve.
Is there a way to find comments in C/C++ which are source code and remove them in order to clean up the code base?
Imagine the following code
// the function foo is doing foo
void foo(){
// bar();
bar2();
}
The old function bar() has been commented out and is no longer used. I like to have an automated way to remove the outdated source code but plain text comments should not be touched. Thus after the clean up the code would look like
// the function foo is doing foo
void foo(){
bar2();
}
I found this and that to remove all comments. This is not what I like to do.
Can clang tidy do this job?
This really scratched my mind, so,
I have written a small program in javascript real quick, which removes the lines that have // and ; in a text just to show.
You can write your own algorithm, and remove lines like that. For example, you can put # sign to the lines you would like to get deleted and then run your program with it. You need to make your own algorithm or just a simple one like mine.
Here is my js code: it deletes the rows and logs the result to the console as an array for example.
You should code a program like this or however you like.
<html>
<textarea id="txtArea" rows="40" cols="300">
// the function foo is doing foo
void foo(){
// bar();
bar2();
}
</textarea>
</html>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
var x = document.getElementById("txtArea").value;
var lines = x.split("\n");
var count = lines.length;
for(var i =0; i< lines.length; i++){
if(lines[i].indexOf("//")){
console.log("haha");
}else{
if(lines[i].indexOf(";")){
lines[i] = "";
//remove row
}else{
}
}
}
document.getElementById("txtArea").value = lines;
var y;
console.log(lines);
</script>

How to return error code from the main function in C++? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am working on an object-oriented C++ coursework where I need to return error codes from the main function. How would one do this properly?
Unfortunately this is an assessed coursework so I cannot post my code here. But let's say the case is as follows:
I'm building an enigma machine with classes Plugboard, Reflector, and Rotor. I pass each of the configuration files as arguments in the command line. In this task, I'm provided with a file errors.h containing the following:
#define INSUFFICIENT_NUMBER_OF_PARAMETERS 1
#define INVALID_INPUT_CHARACTER 2
#define INVALID_INDEX 3
// and so on...
So I have in my program several functions to check the errors, for example a function to check whether the configuration file contains an invalid character (it has to be 0 to 25). I was thinking of setting this as a boolean function and then in my main function have the following:
if (!plugboard.check_invalid_character(/*some arguments*/)) {
cerr << "Invalid character!" << endl;
return 2;
}
But I'm not completely sure this is the right way to do it? Is it too superficial? Is there a more elegant way of returning error?
I hope my question is a little clearer this time. Thanks before.
You just need to return the value 4 in your main method like this:
int main() {
return 4;
}
Please note that your main function could also have the arguments vector and the argument count so there could be more in the brackets.
If KLibby is right and you use a method with returns the value you need to use something like that:
int doSomething() {
return 4;
}
int main() {
return doSomething();
}