【问题标题】:How to fix string declaration error in scope如何修复范围内的字符串声明错误
【发布时间】:2019-10-19 17:18:13
【问题描述】:

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

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

【问题讨论】:

  • 顺便说一句,std::string 的对象可以使用== 运算符进行比较。您应该将所有内容都转换为std::string,以免混淆。
  • 在您的发布的代码中,您从哪里读取文件?
  • 声明参数或变量时不需要使用struct;这是 C++,不是 C。
  • 您不需要 to_string 来从 char* 转换(甚至不存在重载)。而atoi 采用const char*,而不是 std::string`。
  • 修复第一个问题,argv[0] 已经是一个字符串,所以你不需要使用to_string。在您最喜欢的 C++ 参考资料中查找 to_stringstd::string constuctor 的定义

标签: c++ linux ubuntu ipc msgrcv


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多