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