【问题标题】:How to extract 2 integers from a char array C++ and storing them in 2 variables (Beginner)如何从 char 数组 C++ 中提取 2 个整数并将它们存储在 2 个变量中(初学者)
【发布时间】:2018-07-17 10:34:35
【问题描述】:

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

ifStream inData;
inData.open("test.txt');

char range1[40];
inData.getline(range1, 40);

我得到的输出是:

BaseIdRange=0-8

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

非常感谢所有帮助。

【问题讨论】:

标签: c++ arrays char


【解决方案1】:

这是一个适用于 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&lt;char&gt; chars 代替 std::string chars,并将 if 行更改为 if (chars.find(buffer[i]) == chars.end()),但我更喜欢让它更简单 - std::set 的初始化不太明显。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-20
    • 2016-11-27
    • 1970-01-01
    • 2016-10-28
    相关资源
    最近更新 更多