Как исправить ошибку объявления строки в области видимости - PullRequest
0 голосов
/ 19 октября 2019

Я пытаюсь запустить программу межпроцессного взаимодействия, но она говорит, что строка не объявляется в области как есть, и когда я добавляю #inlcude, я получаю сообщение об ошибке:

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);

Это мойкод:

#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);
}

ожидая, что код распечатает сообщение, отправленное из файла отправителя

1 Ответ

0 голосов
/ 19 октября 2019

Вот некоторые исправления для ваших проблем:
string temp = to_string(argv[0]);
1. to_string преобразует числа в строку. argv[0] - это строка в стиле C, а не число.
2. Конструктор std::string уже имеет версию для преобразования из char * в std::string.

atoi(temp)
1. Функция atoi принимает параметр типа char *, а не std::string. Вам нужно будет использовать atoi(temp.c_str()) или предпочитайте std::ostringstream.

Пожалуйста, просмотрите различия между массивами char (иначе говоря, в стиле C) и типом std::string. Предпочитают использовать std::string, особенно в конструкциях.

Внимательно прочитайте описания функций библиотеки перед их использованием.

См. Также std::ostringstream. Поскольку это C ++, предпочтительнее использовать ввод-вывод C ++, например std::cout и operator <<.

...