ifstream and put it in a string

Hello C++'s,

I am trying to open a TEXT file and put it in a string.

string line;

ifstream infile;
infile.open("data_01.LIB");
infile.read(line, 20);

but it gif me a response the line is not a valid, variable.








Two problems.

1) You don't check that the open of the file succeeded.
Always use if (file.is_open()) to check.

2) You can't read directly into line. std:string is not a Plain Old Data (POD) data type.
It keeps information about the string in the object. If you read directly into the object, you wipe out that information. You want getline().
Last edited on
Depending on what you are trying to read it might be a good idea to use std::getline(...). See:

https://cplusplus.com/reference/string/string/getline/?kw=getline

Note that this will read the data until a '\n' is reached. But you might use another delimiter.
To read the whole file into a string, then:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <fstream>
#include <string>
#include <iterator>
#include <iostream>

int main() {
	if (std::ifstream ifs { "data_01.LIB" }) {
		std::string data((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());

		// use data here
		std::cout << data << '\n';
	} else
		std::cout << "Cannot open file\n";
}


[code amended as per below comment]
Last edited on
The most canonical way to read a whole file into a string is to use a stringstream and some RVO:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <string>

std::string file_to_string( const std::string & filename, bool binary = false )
{
  std::ifstream f( filename, binary ? std::ios::binary : 0 );
  if (!f) throw std::runtime_error( "file_to_string: " + filename );

  std::ostringstream ss;
  ss << f.rdbuf();
  return ss.str();
}

Enjoy!
@seeplus you wouldn't need noskipws if you used istreambuf_iterator
True. Thanks. I've changed the code above... :) :)
Last edited on
c++ : seeplus , thnx I works fine now.

Tnx a lot



Topic archived. No new replies allowed.