簡體   English   中英

如何從矢量轉換 <char> 到一個整數

[英]How to convert from vector<char> to a number integer

我有一個帶有['6''''0''0''0']的向量來自輸入60,000的用戶。 我需要一個int 60000,所以我可以操縱這個數字。

我是c ++和編程的新手。 我從一個串口讀取60,000-3,500,000的數據/數字,我需要一個整數,我成功完成這個並打印它的唯一方法是通過std :: vector。 我試着做矢量,但它給了我時髦的數字。

#include "SerialPort.h"
std::vector<char> rxBuf(15);
DWORD dwRead;
while (1) {
  dwRead = port.Read(rxBuf.data(), static_cast<DWORD>(rxBuf.size()));
  // this reads from a serial port and takes in data
  // rxBuf would hold a user inputted number in this case 60,000
  if (dwRead != 0) {
    for (unsigned i = 0; i < dwRead; ++i) {
      cout << rxBuf[i];
      // this prints out what rxBuf holds
    }
    // I need an int = 60,000 from my vector holding [ '6' '0' '0' '0 '0']
    int test = rxBuf[0 - dwRead];
    cout << test;
    // I tried this but it gives me the decimal equivalent of the character
    numbers
  }
}

我需要60000的輸出不在矢量中而是作為一個實數,任何幫助將不勝感激謝謝。

從這個答案 ,你可以做一些事情:

std::string str(rxBuf.begin(), rxBuf.end());

將Vector轉換為String。

之后,您可以使用std :: stoi函數:

int output = std::stoi(str);
    std::cout << output << "\n";

循環遍歷std::vector的元素並從中構造一個int

std::vector<char> chars = {'6', '0', '0', '0', '0'};

int number = 0;

for (char c : chars) {
    number *= 10;
    int to_int = c - '0'; // convert character number to its numeric representation
    number += to_int;
}

std::cout << number / 2; // prints 30000

使用std :: string來構建字符串:

std::string istr;
char c = 'o';
istr.push_back(c);

然后使用std :: stoi轉換為整數; 的std :: Stoi旅館

int i = std::stoi(istr);

C ++ 17添加了std::from_chars函數,它可以執行您想要的操作而無需修改或復制輸入向量:

std::vector<char> chars = {'6', '0', '0', '0', '0'};
int number;
auto [p, ec] = std::from_chars(chars.data(), chars.data() + chars.size(), number);
if (ec != std::errc{}) {
    std::cerr << "unable to parse number\n";
} else {
    std::cout << "number is " << number << '\n';
}

現場演示

要最小化對臨時變量的需求,請使用具有適當長度的std::string作為緩沖區。

#include "SerialPort.h"
#include <string>

std::string rxBuf(15, '\0');
DWORD dwRead;

while (1) {
    dwRead = port.Read(rxBuf.data(), static_cast<DWORD>(rxBuf.size()));

    if (dwRead != 0) {
        rxBuf[dwRead] = '\0'; // set null terminator
        int test = std::stoi(rxBuf);
        cout << test;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM