如何从字符数组C++中提取2个整数并将它们存储在2个变量中(初学者)
How to extract 2 integers from a char array C++ and storing them in 2 variables (Beginner)
我设法从.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
的初始化不太明显
相关文章:
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 在c++中获取两个大int,并将它们存储在数组中
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 为什么 bool 和 _Bool 如果它们在内存中占用 1 个字节,它们只能存储 0 或 1
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- Boost program_options将多个配置文件解析结果存储到一个parsed_options中
- 如何存储包含多个空格的字符串 c++
- 单个变量如何存储多个值?
- 如何在 c++ 中存储具有值的四个参数的元组
- 初始化一个由 p 指向的新 INTSTK,它最多可以存储 m 个
- 为什么具有静态存储持续时间的同一内联变量在包含在 VS2017 编译的两个翻译单元中时会构造和销毁两次
- C++ 如何在包含两个变量的结构中存储与变量不同数量的值?
- 将一个阵列中的数据存储到另外两个阵列中不起作用
- 一个 2D 数组,并按行存储值.第一个循环用于行索引,第二个循环用于列索引
- git 子模块的替代方案,用于使用多个存储库的项目
- 可以读/写EEPROM地址,但是只能读/写第一个存储页面
- 关于从第二个存储值_ty2秒复制std :: Map Iterator的数据的问题
- 使用带有boost::program_options的多个源时,请使用最后一个存储值,而不是第一个存储值
- c++错误3错误C2159:指定了多个存储类
- 如何提高具有100万个元素和997个存储桶的哈希表的性能