-
January 8th, 2014, 04:13 AM
#1
get data from input stream c++
Code:
#include <fstream>
#include <string>
using namespace std;
ifstream inf("file name");
string line;
while (inf.good()) {
getline(inf, line);
}
instead of line by line i want the complete data from file to the string.What modification i have to do?
-
January 8th, 2014, 04:25 AM
#2
Re: get data from input stream c++
Victor Nijegorodov
-
January 8th, 2014, 04:33 AM
#3
Re: get data from input stream c++
There are a few ways, e.g., you could read line by line and then append to a string. However, one way that comes to mind is:
Code:
#include <fstream>
#include <sstream>
#include <string>
int main()
{
using namespace std;
ifstream inf("file name");
stringstream ss;
ss << inf.rdbuf();
string content = ss.str();
// ...
}
By the way, your method of reading line by line is wrong. You should not be calling inf.good() to control the loop. Rather:
Code:
while (getline(inf, line)) {
// ...
}
-
January 8th, 2014, 05:30 AM
#4
Re: get data from input stream c++
Here's another way
Code:
#include <fstream>
#include <string>
int main()
{
std::string str;
std::ifstream inf("file name");
inf.seekg(0, std::ios::end);
str.resize(inf.tellg());
inf.seekg(0, std::ios::beg);
inf.read(&str[0], str.size());
}
Cheers, D Drmmr
Please put [code][/code] tags around your code to preserve indentation and make it more readable.
As long as man ascribes to himself what is merely a posibility, he will not work for the attainment of it. - P. D. Ouspensky
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|