如何将vector<char>转换为整数?

3

我有一个向量,它包含[ '6' '0' '0' '0' '0'],这是由用户输入的60,000。我需要一个整数60000,以便可以对这个数字进行操作。

我是c++和编程方面的新手。我从串口读取60,000-3,500,000的数据/数字,并且我需要一个整数,我唯一成功完成并打印的方法是使用std::vector。 我试过使用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,而不是作为一个向量。任何帮助将不胜感激,谢谢。


可能是将字符向量转换为整数的重复问题。 - Heath Raftery
1
你对 rxBuf[0 - dwRead] 有什么期望?有一个严重的误解需要纠正。你认为这是 Python 中列表切片的等价物吗? - LogicStuff
不如跳过 vector,改用 std::string rxBuf(15, 0);,然后使用它呢? - Ted Lyngmo
您的问题实际上与向量没有多大关系,因为向量将其数据存储在连续的内存中,与char数组没有什么不同。因此,如果您问“如何将char数组转换为int”,答案将是相同的。 - PaulMcKenzie
5个回答

9

从这个答案,你可以做出如下操作:

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

将您的向量转换为字符串。
之后,您可以使用std::stoi函数:
int output = std::stoi(str);
    std::cout << output << "\n";

2
注意:如果向量字符串仍然以空终止符结尾,则可以直接使用std::stoi(rxBuf.data()) - DColt

5

遍历 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

不像其他答案那么雄辩,但能完成任务。 - user10957435
我更喜欢这个答案,因为它不依赖于std::stringstd::stoi - 没有内存分配或不必要的检查。虽然我更喜欢使用std::uint32_t而不是int - Quimby

3
使用std::string来构建你的字符串:
std::string istr;
char c = 'o';
istr.push_back(c);

然后使用std::stoi将其转换为整数; std::stoi
int i = std::stoi(istr);

3

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';
}

现场演示


2
为了减少临时变量的需求,可以使用具有适当长度的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;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接