c++ - 如何修复范围内的字符串声明错误

标签 c++ linux ubuntu ipc msgrcv

我正在尝试运行进程间通信程序,但它说字符串未按原样在范围内声明,当我添加 #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);
}

期望代码打印出从发件人文件发送的消息

最佳答案

以下是针对您的问题的一些修复:
string temp = to_string(argv[0]);
1. to_string 将数字转换为字符串。 argv[0]是 C 风格的字符串,而不是数字。
2.std::string constructor已有一个版本可从 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++ I/O,例如 std::coutoperator << .

关于c++ - 如何修复范围内的字符串声明错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58466152/

相关文章:

c++ - 无法从 gethostname 访问 IP 地址的内存

c++ - 如何修复 Microsoft typeinfo.name() 内存泄漏?

linux - "The directory name/app/Views/is invalid"在使用 docker 的 ASP.NET Core 部署上

python - 如何从Python脚本在Ubuntu中创建可执行文件+启动器?

ubuntu - Sinatra + Thin 的 Systemd 服务不断重启

c++ - 由于父类(super class)(按值传递)导致的重载构造函数调用不明确

c++ - wdk 中的新建和删除

linux - 从 bash 中的文件行获取字符串

php - 在 LINUX 服务器上从 PHP 启动 python 文件

gcc - 在 Ubuntu 10.10 32 位上构建 gcc-4.0.4。检测到缓冲区溢出