Rune Allnor
11/9/2008 4:42:00 PM
On 9 Nov, 16:20, Obnoxious User <O...@127.0.0.1> wrote:
> On Sun, 09 Nov 2008 06:02:50 -0800, Rune Allnor wrote:
> > Hi all.
>
> > I am trying to use std::stringstream to validate input from a file. The
> > strategy is to read a line from the file into a std::string and feed
> > this std::string to an object which breaks it up into individual
> > elements. The elements can be strings, integers or floating point
> > numbers.
>
> > In the object where I break the line into elements I use a
> > std::stringstream object to do the actual check:
>
> > std::stringstream ss_;
> > std::string destination1;
> > std::string destination2;
>
> > ss_ << source.substr(i,j-i);
> > ss_ >> destination1;
> > // destination1 contains the desired string ss_.str(""); // Prep
> > for the next item
>
> > // update i and j
>
> > // Preferred syntax
> > ss_ << source.substr(i,j-i);
> > ss_ >> destination2;
> > // destination2 is empty
>
> > This works, but only partially: The destination1 string contains the
> > desired result, but the destination2 string always comes up empty.
>
> > The alternative implementation,
>
> > std::string tmp = source.substr(i,j-i);
> > // Tmp now contains the desire result
> > ss_ << tmp;
> > ss_ >> destination2;
>
> > shows that I am able to extract the desired substring, but for some
> > reason the std::stringstream object doesn't work.
>
> > Any ideas what might be wrong?
> > Any suggestions about other ways of reading/validating file I/O? Regular
> > expressions is one option, but it seems to be a nightmare to cover all
> > those different number formats for floating point...
>
> Post a minimal compilable program that demonstrates the
> error you perceive.
Code appended below. Of course, I don't validate strings
in this way - I had in mind to use this technique to
validate numbers - but it would help to know what is
going on.
And even if I choose regular expressions to validate
the text, it seems I need some similar trick to convert
numbers from text to binary, similar to C's scanf().
Rune
//#include "stdafx.h" // Compiled with VS2005
#include <sstream>
#include <iostream>
#include <string>
int main(int argc, char* argv[])
{
std::string source1("Text1");
std::string source2("Text2");
std::string dest1;
std::string dest2;
std::stringstream ss;
ss << source1;
ss >> dest1;
std::cout << dest1.c_str() << std::endl; // Works as expected
ss.str("");
ss << source2;
ss >> dest2;
std::cout << dest2.c_str() << std::endl; // Prints a blank line
return 0;
}