-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).

5
  • No, ifstream is designed to read a file. You can use std::stringstream if you want to feed a std::string as an istream. Commented Jul 6, 2017 at 18:30
  • 1
    std::istringstream Commented Jul 6, 2017 at 18:30
  • It's completely unclear what you're asking for. Do you get the string to read from as argument of you program, or do you want to read a file's content into a std::string? Commented Jul 6, 2017 at 18:56
  • In my answer below I completely ignore your mention of argc and argv, which seem to make no sense. Commented Jul 6, 2017 at 19:08
  • @user0042 I'm getting it as an argument to my program. Commented Jul 6, 2017 at 20:19

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.