std::wistringstream
is a great way to easily parse lines from files.
However, there is one use case that it doesn't seem to be able to handle :
When parsing a std::wstring
, it will consider any space in the string as the end of said string.
For example, if my file contains these lines :
This_is_a_test 42
Bad string name 747
If I attempt to parse a string and number, first one will succeed but the second one will fail.
If I change the file content with the following :
"This_is_a_test" 42
"Bad string name" 747
The parsing of the second string will still fail despite the "
. Is there a trick to make the std::wistringstream
ignore spaces within the string ? Something similar in principle to the "
.
Is it a use case that this parsing method cannot handle ?
Code sample to try and parse the file :
#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;
}
Output with the examples presented :
The line This_is_a_test 42 is properly formatted
The line Bad string name 747 is NOT properly formatted
and
The line "This_is_a_test" 42 is properly formatted
The line "Bad string name" 747 is NOT properly formatted