【问题标题】:Reading formatted text from input stream [duplicate]从输入流中读取格式化文本[重复]
【发布时间】:2018-09-05 21:22:57
【问题描述】:

我有一个 .txt 文件,我希望从中获得某种行格式,其中包含我需要保留的数据。

例如:

输入.txt:

Number: 654
Name: Alon
-----

我需要:

1.将 654 和“Alon”提取到相应的变量中。

2。如果格式不准确,则抛出错误。

如果这是 C,我可能会使用:

if (fscanf(inputFile, "Number: %d", &num) == 0)
{
    // raise an error
}

假设使用 C 的函数不是一个好主意,我剩下的 std::cin 可能让我可以访问我需要提取的数据,但无法控制包装数据的字符串的确切格式。

我已经使用 .我还使用 std::getline(...) 检索了第一行。 这就是我所拥有的:

std::ifstream inputFile;
string lineToParse;
inputFile.open("input.txt", std::fstream::in);
if (inputFile.fail())
{
    // throw exception
}
else
{
    std::getline(inputFile, lineToParse);
    int data;
    inputFile >> data;
}

假设 input.txt 是上面的文件,我希望 lineToParse 是“数字:654”,数据是 654。 但正如我所说,我无法通过这种方式控制行的格式。

有什么想法吗?

【问题讨论】:

标签: c++ string input


【解决方案1】:

您可以使用std::getline 解析到特定字符,例如':'

类似:

int line_number = 0;
while(std::getline(inputFile, lineToParse))
{
    ++line_number;

    // check for empty lines here and skip them

    // make a stream out of the line
    std::istringstream iss(lineToParse);

    std::string key, value;
    if(!std::getline(std::getline(iss, key, ':') >> std::ws, value))
    {
        std::cerr << "bad format at line: " << line_number << '\n';
        continue;
    }

    // do something with key and value here...
}

你有你的keyvalue key 应该告诉你如何转换值(无论是整数、浮点数、日期/时间等......)。

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 2013-09-02
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2012-03-09
    • 2017-08-06
    • 2013-06-03
    相关资源
    最近更新 更多