ifstream and put it in a string

Aug 9, 2022 at 8:27pm
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.








Aug 9, 2022 at 8:37pm
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 Aug 9, 2022 at 8:39pm
Aug 10, 2022 at 6:41am
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.
Aug 10, 2022 at 9:09am
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 Aug 10, 2022 at 3:26pm
Aug 10, 2022 at 12:40pm
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!
Aug 10, 2022 at 1:26pm
@seeplus you wouldn't need noskipws if you used istreambuf_iterator
Aug 10, 2022 at 3:25pm
True. Thanks. I've changed the code above... :) :)
Last edited on Aug 10, 2022 at 3:29pm
Aug 10, 2022 at 8:20pm
c++ : seeplus , thnx I works fine now.

Tnx a lot



Topic archived. No new replies allowed.