RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-449217

Anton-Vas's questions

Martin Hope
Anton-Vas
Asked: 2022-07-01 21:01:00 +0000 UTC

如何存储/使用来自单独文件的参数数组?

  • 0

Param.c文件包含几个全局数组,用于存储多个参数并与之交互。为了使用它们,我在必要的文件中应用了数组的extern ,但Param.c中的警告并没有消失。

'Param..' 已定义但未使用

如果把extern去掉,给数组加上static,那么控制台上会显示数组的 null 值。但是,接受参数的 MissionPlanner 将正确显示所有参数!请告诉我如何解决这种情况。

示意图代码:

|
|_main.h
| |_main.c
|
|_Params.c
|
|_Func.h
  |_Func.c

-------<main.c>-------
#include"main.h"
#include"Params.c"

extern float ParamValue[];

int main(..){
    GetVal();
    while(1){
        Print(ParamValue[PARAM_4]); //Custom debug print to UART(FTDI)
        SendVal(ParamValue[PARAM_4]);
    }
}

------<Params.c>------
enum ParamID{   PARAM_1=0,
                PARAM_2=1,
                PARAM_3,
                PARAM_4,
                PARAM_END};
float ParamValue[] = {  1.0f,
                        2.0f,
                        3.0f,
                        0.0f};

-------<Func.h>-------
#include "main.h"

void GetVal();
void SendVal(const float _param);

-------<Func.c>-------
#include"Func.h"
#include"Params.c"

extern float ParamValue[];

void GetVal(){
    ParamValue[PARAM_4] = 4.0f; 
}
void SendVal(const float _param){
    //Send via UART to MissionPlanner
}

PS:我知道在多个文件中使用全局变量很危险。但是我没有想出另一种存储参数的方法。如果有人有任何建议,我很想听听!

c
  • 1 个回答
  • 10 Views
Martin Hope
Anton-Vas
Asked: 2022-05-01 21:27:05 +0000 UTC

STM32 不接受通过 UART 的 MAVLink 命令

  • 0

来自一篇关于将自动驾驶仪连接到机上附加计算机的精彩文章 ( https://discuss.ardupilot.org/t/mavlink-and-arduino-step-by-step/25566 ) 的源代码。

我为我的任务重做了它,但原理保持不变。与源的唯一区别是不同的微控制器。我在 Arduino MINI 上进行了测试,但对于未来的升级来说还不够。因此,我将代码转移到 STM32 轨道上,复杂性就出现了。

- - - - - - - - - - - - - - - - - - - - - - - 问题 - - --------------------------------------------------

  • 在下面的代码中,不接受请求的命令!

我尽量不改变文章作者的方法,但没有直接模拟 Arduino HAL 函数:available()。所以我尝试用更合适的 HAL_UART_GetState() 替换它。

  • 目前尚不清楚问题是什么:while(...)条件或几个HAL_UART_Receive_IT / _Transmit的冲突

用 STM32CubeIDE 编写,MAVLink 库来自文章,STM32F411CEU6 微控制器,通过 Termite 上的 UART (FTDI Arduino) 输出消息。

#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "mavlink.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
    ///< Temporary here:
#define MAV_TYPE_GIMBAL 26
#define MAV_COMP_ID_GIMBAL 154

    ///< Debug:
#define DEBUG_MODE
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
unsigned long previousMillisMAVLink   = 0;                       ///< will store last time MAVLink was transmitted and listened
unsigned long nextIntervalMAVLink     = 1000;                    ///< next interval to count
const int     c_num_hbs               = 60;                      ///< № of heartbeats to wait before activating STREAMS from Pixhawk. 60 = one minute.
int           num_hbs_pasados         = c_num_hbs;

    /*MAVLink variables*/
int           sysid                   = 1;                       ///< ID 1: id of plane (stm32 is planes` component)
int           compid                  = MAV_COMP_ID_GIMBAL;      ///< The component sending the message
int           type                    = MAV_TYPE_GIMBAL;         ///< Gimbal

    /*Define the system type, in this case an airplane -> on-board controller*/
uint8_t       system_type             = MAV_TYPE_GENERIC;
uint8_t       autopilot_type          = MAV_AUTOPILOT_INVALID;
uint8_t       system_mode             = MAV_MODE_PREFLIGHT;      ///< Booting up
uint8_t       system_state            = MAV_STATE_STANDBY;       ///< System ready for flight
uint8_t       req_stream_id           = MAV_DATA_STREAM_ALL;
uint8_t       target_system           = 1;                       ///< Id # of Pixhawk (should be 1)
uint8_t       target_component        = 0;                       ///< Target component, 0 = all (seems to work with 0 or 1
uint8_t       start_stop              = 1;                       ///< 1 = start, 0 = stop
uint16_t      req_message_rate        = 0x01;                    ///< number of times per second to request the data in hex
uint32_t      custom_mode             = 0;                       ///< Custom mode, can be defined by user/adopter
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
/* USER CODE BEGIN PFP */
void debugPrint(UART_HandleTypeDef *huart, char _out[]);
void debugPrintln(UART_HandleTypeDef *huart, char _out[]);
void MavLink_Receive();
void Request_Datastream();
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  /* USER CODE BEGIN 2 */
#ifdef DEBUG_MODE
  debugPrintln(&huart1, " STM32F411CEU6.........ACTIVE");
#endif

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
      mavlink_message_t msg;
      uint8_t buf[MAVLINK_MAX_PACKET_LEN];

         /*Pack the message*/
      mavlink_msg_heartbeat_pack( sysid, compid, &msg, type, autopilot_type, system_mode, custom_mode, system_state);

         /*Copy the message to the send buffer*/
      uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

      unsigned long currentMillisMAVLink = HAL_GetTick();

      if (currentMillisMAVLink - previousMillisMAVLink >= nextIntervalMAVLink) {
              /* Save the last time you changed the mode */
          previousMillisMAVLink = currentMillisMAVLink;

          HAL_UART_Transmit(&huart2, (uint8_t*)buf, len, 100);

#ifdef DEBUG_MODE
          if(sizeof(buf)){
              debugPrintln(&huart1, " HB......................SENT");
          }
#endif

          num_hbs_pasados++;
          if(num_hbs_pasados>=c_num_hbs) {
              Request_Datastream();
              num_hbs_pasados=0;
          }
      }

      MavLink_Receive();

    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 12;
  RCC_OscInitStruct.PLL.PLLN = 96;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 57600;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 57600;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

}

/* USER CODE BEGIN 4 */
void debugPrint(UART_HandleTypeDef *huart, char _out[]){
    HAL_UART_Transmit(huart, (uint8_t *) _out, strlen(_out), 100);
//  HAL_UART_Transmit_IT(huart, (uint8_t *) _out, strlen(_out));
}

void debugPrintln(UART_HandleTypeDef *huart, char _out[]){
    HAL_UART_Transmit(huart, (uint8_t *) _out, strlen(_out), 100);
//  HAL_UART_Transmit_IT(huart, (uint8_t *) _out, strlen(_out));
    char newline[2] = "\r\n";
    HAL_UART_Transmit(huart, (uint8_t *) newline, 2, 100);
//  HAL_UART_Transmit_IT(huart, (uint8_t *) newline, 2);
}

void MavLink_Receive(){

    mavlink_message_t msg;
    mavlink_status_t status;

    while(HAL_UART_GetState(&huart2)==HAL_UART_STATE_READY){           //
                                                                       //
        uint8_t c;                                                     //.......?
//      HAL_UART_Receive(&huart2, &c, 1, 100);                         //
        HAL_UART_Receive_IT(&huart2, &c, 1);                           //

        if(mavlink_parse_char(MAVLINK_COMM_0, c, &msg, &status)) {

#ifdef DEBUG_MODE
            debugPrint(&huart1, " MSG ID: ");
            debugPrintln(&huart2, msg.msgid);
#endif

            switch(msg.msgid){
                case MAVLINK_MSG_ID_COMMAND_LONG:{

#ifdef DEBUG_MODE
                    debugPrintln(&huart1, " >>>Income_MSG.....COMMAND_LONG");
#endif
                    /*Send confirmation to GCS through PX4*/
                    mavlink_message_t resMsg;
                    uint8_t resBuf[MAVLINK_MAX_PACKET_LEN];
                    mavlink_msg_command_ack_pack(sysid, compid, &resMsg, MAV_CMD_DO_MOUNT_CONTROL, MAV_RESULT_ACCEPTED);
                    uint16_t resLen = mavlink_msg_to_send_buffer(resBuf, &resMsg);

#ifdef DEBUG_MODE
                    debugPrint(&huart1, "..........MSG ID: ");
                    debugPrintln(&huart1, msg.msgid);
                    if(resLen){
                        debugPrintln(&huart1, " >>>Income_MSG.....CONFIRM");
                    }
#endif
                    HAL_UART_Transmit(&huart2, (uint8_t*)resBuf, resLen, 100);
                }
                break;
#ifdef DEBUG_MODE
//              default:
//                  debugPrintln(&huart1, " >>>Income_MSG........NO_SIMILAR");
//                  break;
#endif
            }
        }
    }
}
void Request_Datastream() {

    /*Initialize the required buffers*/
    mavlink_message_t msg;
    uint8_t buf[MAVLINK_MAX_PACKET_LEN];

    /*Pack the message*/
    mavlink_msg_request_data_stream_pack( sysid, compid, &msg, target_system, target_component, req_stream_id, req_message_rate, start_stop);
    uint16_t len = mavlink_msg_to_send_buffer(buf, &msg);

#ifdef DEBUG_MODE
    debugPrintln(&huart1, " MAVLink..............REQUESTED");
#endif

  HAL_UART_Transmit(&huart2, (uint8_t*)buf, len, 100);
}
/* USER CODE END 4 */
c++
  • 1 个回答
  • 10 Views
Martin Hope
Anton-Vas
Asked: 2022-03-13 18:14:13 +0000 UTC

无法将 [undefined] 分配给 RadioButton 的 bool

  • 0

我在章节顶部有一些项目。窗户。其中的任务是选择操作模式,然后窗口关闭并显示章节。窗户。我还没有绑定 C++ 类,所以大多数类似的问题都没有帮助。发生错误:在第二种情况下无法将 [undefined] 分配给 bool。

发生:

1-在正确的项目中创建两个自定义单选按钮-> 全部确定;

2- 从单独的文件中调用所需项目中的两个自定义单选按钮->可见错误:parent.checked。

DarkRadioButton.qml

import QtQuick 2.14
import QtQuick.Controls 2.14

RadioButton {

    checked: false

    indicator: Rectangle {
        implicitWidth: 20
        implicitHeight: 20
        x: payloadRole.horizontalPadding
        y: payloadRole.height / 2 - height / 2
        radius: 0
        border.color: Qt.rgba( 255/255., 0/255., 0/255., 1)
        color: Qt.rgba( 32/255., 32/255., 32/255., 1)

        Rectangle {
            id: radioButtonBox
            width: 16
            height: 16
            x: 2
            y: 2
            Image {
                anchors.fill: radioButtonBox
                source: "qrc:/res/resources/DarkRadioButtonBox.png"
                fillMode: Image.PreserveAspectCrop
                sourceSize.width: 200
                sourceSize.height: 200
            }
            visible: parent.checked             //!!!!!!!!!! ошибка !!!!!!!!!!!!
        }
    }
    contentItem: Text {
        text: parent.text
        font: parent.font
        color: Qt.rgba( 255/255., 255/255., 255/255., 1)
        verticalAlignment: Text.AlignVCenter
        leftPadding: parent.indicator.width + parent.spacing
    }
    onCheckedChanged: {
        //some extern value function (not here yet)
        optionsWindow.visible = false
    }
}

通话地点:有条件的main.qml

//--- 
Item {
         //---
         ColumnLayout{
                        width:  dialog.width
                        height:  dialog.height
        
                        DarkRadioButton {
                            id: optionA
                            text: qsTr("Option 1")
                            Layout.alignment: Qt.AlignCenter
                        }
                        DarkRadioButton {
                            id: optionB
                            text: qsTr("Option 2")
                            Layout.alignment: Qt.AlignCenter
                        }

关闭项目有效,但我计划继续使用此模板。我不知道这个错误是否会干扰,所以我决定寻求帮助。

qtcreator
  • 1 个回答
  • 10 Views
Martin Hope
Anton-Vas
Asked: 2022-10-06 16:50:47 +0000 UTC

如何正确学习 QML?

  • 2

我正在学习 QML,例如我决定反汇编一个开源应用程序。问题是有超过一百个 .qml 文件......

是否有任何应用程序可以在文件之间以例如图形的形式进行继承?或者你将不得不用手一个接一个地检查文件,在一张纸上写下研究结果。

我了解 QML 的概念,但我想创建这些文件的映射。该程序是用QtCreator编写的,也许它有类似的功能?

qtcreator
  • 1 个回答
  • 10 Views
Martin Hope
Anton-Vas
Asked: 2022-08-31 17:49:36 +0000 UTC

如何将小部件设置为调整大小以匹配主窗口的大小?

  • 1

我决定学习如何编写自己的应用程序,但遇到了对Qt Designer的误解。

完成任务:

这是更详细的想法。已经建议实施:如何在主窗口中创建个人小部件?

短的:

我想在一个窗口中编写一个简单的程序。它有 3 个独立的子窗口(见截图,大概显示了一些东西)。有人建议我使用 QSplitter。这解决了该问题,但出现了以下问题。

问题:

  1. 如何通过主窗口调整大小来实现小部件调整大小?
  2. 这可以在 Qt Designer 中完成吗?

我看到了类似的问题,但他们使用固定模板(按钮、文本、窗口等)创建了窗口。同时,我有可以手动调整大小的实时窗口。此外,如果我为Central 小部件选择LayOut,我将无法为 3 个窗口创建拆分器 (在我的情况下是 QFrame,因为将来我将在那里添加功能)

  1. 是否可以在同一个 Qt Designer 中添加放大条件?

我希望在不改变 1x1 纵横比的情况下,深灰色和浅绿色窗口与主窗口一起增长。

在此处输入图像描述

更新

ui文件。我想手动做菜单栏,所以值得考虑。

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>GcsWindow</class>
 <widget class="QMainWindow" name="GcsWindow">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1000</width>
    <height>600</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>GcsWindow</string>
  </property>
  <property name="styleSheet">
   <string notr="true"/>
  </property>
  <widget class="QWidget" name="centralwidget">
   <property name="minimumSize">
    <size>
     <width>1000</width>
     <height>600</height>
    </size>
   </property>
   <property name="sizeIncrement">
    <size>
     <width>1</width>
     <height>1</height>
    </size>
   </property>
   <property name="baseSize">
    <size>
     <width>1000</width>
     <height>600</height>
    </size>
   </property>
   <widget class="QPushButton" name="BUT_Menu">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>0</y>
      <width>80</width>
      <height>30</height>
     </rect>
    </property>
    <property name="sizePolicy">
     <sizepolicy hsizetype="Expanding" vsizetype="Expanding">
      <horstretch>0</horstretch>
      <verstretch>0</verstretch>
     </sizepolicy>
    </property>
    <property name="styleSheet">
     <string notr="true">QPushButton {
    background-color: rgb(235,235,235);
    border-radius: 1px;
    Text-align:center;

}
QPushButton:hover{
    background-color:rgb(225, 225, 225);
}
QPushButton:pressed {
    background-color: rgb(200,200,200);
    border-style: inset;
}
QPushButton:open{
    background-color: rgb(200,200,200);
    border-style: inset;
}</string>
    </property>
    <property name="text">
     <string>MENU</string>
    </property>
   </widget>
   <widget class="QSplitter" name="splitter_2">
    <property name="geometry">
     <rect>
      <x>0</x>
      <y>31</y>
      <width>1000</width>
      <height>569</height>
     </rect>
    </property>
    <property name="orientation">
     <enum>Qt::Horizontal</enum>
    </property>
    <property name="handleWidth">
     <number>1</number>
    </property>
    <widget class="QSplitter" name="splitter">
     <property name="baseSize">
      <size>
       <width>0</width>
       <height>0</height>
      </size>
     </property>
     <property name="orientation">
      <enum>Qt::Vertical</enum>
     </property>
     <property name="handleWidth">
      <number>1</number>
     </property>
     <widget class="QFrame" name="frame">
      <property name="baseSize">
       <size>
        <width>300</width>
        <height>300</height>
       </size>
      </property>
      <property name="styleSheet">
       <string notr="true">background-color: rgb(49, 49, 49);</string>
      </property>
      <property name="frameShape">
       <enum>QFrame::StyledPanel</enum>
      </property>
      <property name="frameShadow">
       <enum>QFrame::Raised</enum>
      </property>
     </widget>
     <widget class="QFrame" name="frame_2">
      <property name="baseSize">
       <size>
        <width>300</width>
        <height>269</height>
       </size>
      </property>
      <property name="styleSheet">
       <string notr="true">background-color: rgb(213, 255, 216);</string>
      </property>
      <property name="frameShape">
       <enum>QFrame::StyledPanel</enum>
      </property>
      <property name="frameShadow">
       <enum>QFrame::Raised</enum>
      </property>
     </widget>
    </widget>
    <widget class="QFrame" name="frame_3">
     <property name="styleSheet">
      <string notr="true">background-color: rgb(248, 194, 255);</string>
     </property>
     <property name="frameShape">
      <enum>QFrame::StyledPanel</enum>
     </property>
     <property name="frameShadow">
      <enum>QFrame::Raised</enum>
     </property>
    </widget>
   </widget>
  </widget>
 </widget>
 <resources/>
 <connections/>
</ui>

c++
  • 1 个回答
  • 10 Views
Martin Hope
Anton-Vas
Asked: 2022-06-25 00:20:48 +0000 UTC

如何将文件中具有不同数字分隔的多行计算为单独的向量?

  • 0

我刚刚开始练习复杂的任务,但在构建复杂系统时仍然遇到了麻烦。所以不要评判太苛刻

一个任务:

1- 从 txt 文件中读取几行(参见示例)并将它们转换为(分别为 3 个)单独的向量;

2-考虑不同的“标点符号”(见示例);

我无法通过函数将翻译逻辑正确写入向量。发布的代码版本会读取整个第一个数组,并逐个读取第一个知道的下一个数组。

txt 示例

一个文件有 3 行。

1 2 3 4 5 6 7 8 9 10

11,12,13,14,15,16,17

21、22、23、24、25

  • 不同长度
  • 数字是整数,可以是随机的(我选择了一个简单的例子)
  • 数字分隔类型:PASS、COMA、COMA + PASS

编码

#include<iostream>
#include<vector>
#include<string>
#include<fstream>
#include<algorithm>
#include<sstream>

std::vector<int>Read_Func(const std::string file_name, const char symbol) {

  std::string str;
  std::vector<int>vec_int_tmp;
  std::ifstream in_file(file_name, std::ios::in | std::ios::binary);

  while (!in_file.eof()) {
    getline(in_file, str, '\r');
    std::stringstream iss(str);
    if (symbol==' ') {
      int num;
      while (iss >> num) 
        vec_int_tmp.push_back(num);
    }
    if (symbol==',') {
      std: :replace(str.begin(), str.end(), ',', ' ');
      int num;
      while (iss >> num) 
        vec_int_tmp.push_back(num);
    }
    if (symbol==', ') {
      std: :replace(str.begin(), str.end(), ',', ' ');
      int num;
      while (iss >> num) 
        vec_int_tmp.push_back(num);
    }
    count++;
  }
  
  //Print Messages (Error and others)

  in_file.close();
  return vec_int_tmp;
}

int main() {
  std::string file_name {"C:/.../Given_array.txt"};
  
  std::vector<int>vec_space;
  std::vector<int>vec_both;
  std::vector<int>vec_coma;
  
  vec_space=Read_Func(file_name, ' ');
  vec_coma=Read_Func(file_name, ',');
  vec_both=Read_Func(file_name, ', ');
}

>>> 更新 <<<

最终代码如下所示。特别感谢哈利。

std::vector<std::vector<int>> readFile(std::istream& in)
{
    std::vector<std::vector<int>> v;
    std::string buf;
    while (getline(in, buf))
    {
        replace(buf.begin(), buf.end(), ',', ' ');
        std::istringstream is(buf);
        std::vector<int> b;
        copy(std::istream_iterator<int>(is), std::istream_iterator<int>(),
            back_inserter(b));
        v.push_back(b);
    }
    return v;
}

int main() {
    std::string file_name{ "C:/.../Given_array.txt" };
    std::ifstream in_file;
    in_file.open(file_name, std::ios_base::in);
    std::vector<std::vector<int>> vec_int;
    vec_int = readFile(in_file);
  }

c++
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5