c++ - 解析时 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 格式不正确
解决方案
推荐阅读
- firebase - 使用 @nuxtjs/firebase 在 Nuxt 中使用 Cloud Firestore 生成动态路由
- azure - 用于 OneDrive for business 代码流的重定向 url 是什么?
- firebase - Google Analytics 事件参数仅显示在过去 30 分钟内的事件中
- .net-core - 通过自定义 NuGet 包向 appsettings.json 添加日志记录条目
- javascript - 创建基于 API 的星级评分系统
- spring-boot - 如何使用连接表加载相互关系@OneToMany的2个实体的完整图表
- azure-functions - azure 函数应用程序配置中的 APPINSIGHTS_INSTRUMENTATIONKEY
- charts - 仅部分标签的 chart.js 行
- azure - 如何在 Azure 中删除服务器时发出警报?
- r - 如何在 R 中确定日期间隔是否与数据框中同一个人的另一个日期间隔重叠?