【问题标题】:C++ Problem on setting the serial com port设置串口的C++问题
【发布时间】:2019-01-31 07:41:05
【问题描述】:

在我的 C++ 程序上设置串行 COM 端口时遇到问题。 下面是我的代码。

#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>
#include"SerialPort.h"

char output[MAX_DATA_LENGTH];
char incomingData[MAX_DATA_LENGTH];

char *port = "\\\\.\\COM7";

int main(){
SerialPort arduino(port);
if(arduino.isConnected()){
    cout<<"Connection made"<<endl<<endl;
}
else{
    cout<<"Error in port name"<<endl<<endl;
}
while(arduino.isConnected()){
    cout<<"Enter your command: "<<endl;
    string data;
    cin>>data;

    char *charArray = new char[data.size() + 1];
    copy(data.begin(), data.end(), charArray);
    charArray[data.size()] = '\n';

    arduino.writeSerialPort(charArray, MAX_DATA_LENGTH);
    arduino.readSerialPort(output, MAX_DATA_LENGTH);

    cout<<">> "<<output<<endl;

    delete [] charArray;
    }
return 0;
}

"\\\\.\\COM7"有错误

显示错误消息a value of type "const char *" cannot be used to initialize an entity of type "char *"

当我把它改成const char *port = "\\\\.\\COM7";

SerialPort arduino(port); 显示错误

请帮助我。真的需要一些帮助。谢谢。

【问题讨论】:

  • 项目 > 属性 > C/C++ > 语言 > 一致性模式 = “否”。

标签: c++ visual-c++ visual-studio-2017


【解决方案1】:

在 C++ 中,文字字符串是 常量 字符数组。因此,您需要 const char* 来获取指向它们的指针。

如果必须将非常量指针传递给函数,请使用数组

char port[] = "\\\\.\\COM7";

一个可能更好的解决方案是修改SerialPort 构造函数以接受const char* 作为其参数。或者更好地开始使用std::string 处理字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-06
    • 1970-01-01
    • 2013-07-26
    • 2014-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多