Chr*_*eda 3 c++ type-conversion char stdvector visual-c++
我有一个向量,该向量来自用户输入60,000的['6''0''0''0''0']。我需要一个整数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
}
}
Run Code Online (Sandbox Code Playgroud)
我需要60000的输出(不是向量),而是一个整数,需要任何帮助,谢谢。
根据此答案,您可以执行以下操作:
std::string str(rxBuf.begin(), rxBuf.end());
Run Code Online (Sandbox Code Playgroud)
将Vector转换为字符串。
之后,您可以使用std :: stoi函数:
int output = std::stoi(str);
std::cout << output << "\n";
Run Code Online (Sandbox Code Playgroud)
遍历an的元素std::vector并int从中构造an :
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
143 次 |
| 最近记录: |