So I am trying to input multiple variables on the same line and have it call a function and parse some of the variables to a function it will call. For example the user will enter something like
COMMAND <integer>
I have tried using scanf however when it does work it doesn't seem to recognize the variable I passed. I am certain I am just making a silly mistake but can someone please help me? I wrote a simple program to try to test passing variables like this which I have included below.
#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;
string derp(int test) {
cout << "and here " + test << endl;
return "derp " + test;
}
void main() {
char command[20];
int *bla(0);
scanf("%s %u", &command[0], &bla );
if (strcmp(command, "derp") == 0) {
cout << "works here" << endl;
cout << derp(*bla);
}
}
Change: int *bla(0);
from being a pointer to an actual variable: int bla(0);
Same goes for output: cout << derp(*bla);
to cout << derp(bla);
(no longer need dereferencing on bla).
Also, you can't output a sum of a C-string + an int, it's not concatenation. Use chained output:
cout << "and here " + test << endl;
should be cout << "and here " << test << endl;
and
return "derp " + test;
should be fixed for the same reason.
Fixed version:
#include <iostream>
#include<stdio.h>
#include<string>
using namespace std;
string derp(int test) {
cout << "and here " << test << endl;
return std::string("derp ") + to_string(test);
}
void main() {
char command[20];
int bla(0);
scanf("%s %u", &command[0], &bla);
if (strcmp(command, "derp") == 0) {
cout << "works here" << endl;
cout << derp(bla);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.