如何从向量转换为<char>数字整数

How to convert from vector<char> to a number integer

本文关键字:char gt 数字 整数 lt 向量 转换      更新时间:2023-10-16
我有一个向量,其中 [ '6' '0' '0' '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());

将矢量转换为字符串。

之后,您可以使用 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 转换为整数;标准::斯托伊

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 numbern";
} else {
    std::cout << "number is " << number << 'n';
}

现场演示

若要最大程度地减少对临时变量的需求,请使用具有适当长度的std::string作为缓冲区。

#include "SerialPort.h"
#include <string>
std::string rxBuf(15, '');
DWORD dwRead;
while (1) {
    dwRead = port.Read(rxBuf.data(), static_cast<DWORD>(rxBuf.size()));
    if (dwRead != 0) {
        rxBuf[dwRead] = ''; // set null terminator
        int test = std::stoi(rxBuf);
        cout << test;
    }
}