【发布时间】:2019-11-18 10:00:45
【问题描述】:
我有一个来自用户输入 60,000 的带有 [ '6' '0' '0' '0' '0'] 的向量。我需要一个 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 的输出,而不是一个向量,而是一个实数,感谢任何帮助。
【问题讨论】:
-
您对
rxBuf[0 - dwRead]有什么期望?有一个严重的误解需要纠正。你认为这相当于 Python 的列表切片吗? -
跳过
vector并改用std::string rxBuf(15, 0);怎么样? -
您的问题实际上与向量无关,因为向量将其数据存储在连续内存中,与
char的数组没有什么不同。因此,如果您问“如何将 char 数组转换为int”,答案将是相同的
标签: c++ visual-c++ char type-conversion stdvector