How to fix string declaration error in scope

348 Views Asked by At

I'm trying to run an interprocess communication program but it says string is not declared in the scope as is and when I add #inlcude I get an error that says:

receiver.cpp:25:35: error: invalid conversion from ‘char*’ to ‘int’ [-fpermissive]
     string temp = to_string(argv[0]);
                             ~~~~~~^
In file included from /usr/include/c++/7/string:52:0,
                 from receiver.cpp:14:
/usr/include/c++/7/bits/basic_string.h:6419:3: note: candidate: std::__cxx11::string std::__cxx11::to_string(unsigned int) <near match>
   to_string(unsigned __val)
   ^~~~~~~~~
receiver.cpp:27:26: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’ for argument ‘1’ to ‘int atoi(const char*)’
     int msgid = atoi(temp) //Converts message id from string to integer
                          ^
receiver.cpp:45:32: error: ‘some_data’ was not declared in this scope
     if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1) { //revieces message from message queue
                                ^~~~~~~~~
receiver.cpp:49:29: error: ‘some_data’ was not declared in this scope
     printf("You wrote: %s", some_data.some_text);

This is my code:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.H>
#include <cstring.h>
#include <unist.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <cstdlib>
#inlcude <string>

using namespace std;

struct my_msg_st{
long int my_msg_type;
char some_text[BUFSIZ];
};

int main(int argc, char *argv[0]){
int running =1;
string temp = to_string(argv[0]);
int msgid = atoi(temp);
struct my_msg_st some_data;
long int msg_to_receive = 0;

....

if (strncmp(some_data.some_text, "end", 3) == 0){
    running =0;
}

...
exit(0);
}

expecting for the code to print out the message sent from the sender file

1

There are 1 best solutions below

0
On

Here are some fixes for your issues:
string temp = to_string(argv[0]);
1. to_string converts numbers to string. the argv[0] is a C-style string, not a number.
2. The std::string constructor already has a version to convert from char * to std::string.

atoi(temp)
1. The atoi function takes a parameter of type char * not std::string. You'll need to use atoi(temp.c_str()) or prefer std::ostringstream.

Please review the differences between char arrays (a.k.a. C-Style strings) and the std::string type. Prefer to use std::string, especially in structures.

Carefully read the library function descriptions before using them.

See also std::ostringstream. Since this is C++, prefer to use C++ I/O such as std::cout and operator <<.