如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)

How to extract 2 integers from a char array C++ and storing them in 2 variables (Beginner)

本文关键字:2个 存储 初学者 变量 整数 字符 数组 C++ 提取      更新时间:2023-10-16

我设法从.txt文档中提取了一行,并将其存储在字符数组中

ifStream inData;
inData.open("test.txt');
char range1[40];
inData.getline(range1, 40);

我得到的输出是:

BaseIdRange=0-8

我想将数字0和8存储在两种不同的数据类型中。即int1=0和int2=8

我们非常感谢所有的帮助。

这是一个适用于2个无符号整数的示例:

#include <sstream>
#include <string>
int main()
{
char buffer[32]{ "BaseIdRange=0-8" }; // Input line
// Clean all chars that are not one of 0-9):
std::string chars = "0123456789"; // 'unsigned int' legitimate chars
for (int i = 0; i < sizeof(buffer); i++) {
if (chars.find(buffer[i]) == std::string::npos) // I.e not one of 0-9
buffer[i] = ' ';
}
std::stringstream ss(buffer);
// Extract the 2 integers:
unsigned int data[2]{ 0 };
for (int i = 0; i < 2; i++) {
ss >> data[i];
}
/* 
// Or (instead of the last for):    
unsigned int a = 0, b = 0;
ss >> a;
ss >> b;
*/
return 0;
}
  • 可以使用std::set<char> chars而不是std::string chars,并将if行更改为if (chars.find(buffer[i]) == chars.end()),但我更喜欢保持它更简单-std::set的初始化不太明显
相关文章: