首页 > 解决方案 > 解析时 std::wistringstream 可以忽略字符串中的空格吗?

问题描述

std::wistringstream是从文件中轻松解析行的好方法。

但是,有一个用例似乎无法处理:

解析 astd::wstring时,它会将字符串中的任何空格视为所述字符串的结尾。

例如,如果我的文件包含以下行:

这_is_a_test 42

错误的字符串名称 747

如果我尝试解析字符串和数字,第一个会成功,但第二个会失败。

如果我使用以下内容更改文件内容:

“这_is_a_test” 42

“错误的字符串名称”747

尽管". 是否有std::wistringstream在字符串中忽略空格的技巧?原则上类似于".

这是这种解析方法无法处理的用例吗?

尝试解析文件的代码示例:

#include "stdafx.h"
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>

int main(int argc, wchar_t* argv[])
{
  // Open file
  std::wifstream file("D:\\file.txt", std::fstream::in);

  std::wstring str;
  double number;

  std::wstring line;

  // For each line
  while (getline(file, line))
  {
    std::wistringstream iss(line);

    // We parse the line
    if (!(iss >> str >> number))
      std::wcout << L"The line " << line << L" is NOT properly formatted" << std::endl;
    else
      std::wcout << L"The line " << line << L" is properly formatted" << std::endl;
  }

  return 0;
}

带有示例的输出:

This_is_a_test 42 行格式正确

Bad string name 747 行格式不正确

"This_is_a_test" 42 行的格式正确

行“错误的字符串名称”747 格式不正确

标签: c++stringparsingvisual-c++

解决方案


从 C++14 开始,您可能会使用std::quoted:

iss >> std::quoted(str);

演示


推荐阅读