-1

Currently my programme takes a string as an input which I access using argc and argv

then I use

FILE *fp, *input = stdin;
fp = fopen("input.xml","w+b");
    while(fgets(mystring,100,input) != NULL)
    {
        fputs(mystring,fp);
    }
    fclose(fp);

I did this part only to create a file input.xml which I then supply to

ifstream in("input.xml");
    string s((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());

to get s as a string(basic string). Is there a way to feed my input directly to ifstream? (i.e feeding a string to ifstream).

SilentFlame
  • 487
  • 5
  • 15

2 Answers2

1

Let me get this straight:

  1. You read a string from standard input
  2. You write it to a file
  3. You then read it from the file
  4. And use the file stream object to create a string

That's crazy talk!

Drop the file streams and just instantiate the string from STDIN directly:

string s(
   (std::istreambuf_iterator<char>(std::cin)),
   std::istreambuf_iterator<char>()
);

Remember, std::cin is a std::istream, and the IOStreams part of the standard library is designed for this sort of generic access to data.

Be aware, though, that your approach with std::istreambuf_iterator is not the most efficient, which may be a concern if you're reading a lot of data.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

If I get it right then you want to read all the text provided through standard input into a string.

An easy way to achieve this could be the use of std::getline, which reads all the bytes up to a specific delimiter into a string. If you may assume that it is text content (which does not contain any \0-character), you could write the following:

std::string s;
std::getline(cin,s,'\0');
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58