Read a file with header

Hello I need read a file with header and I wanna print the file in output. How can I do that? I tried but not work..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<fstream>
 using namespace std;
 
 int main()
 { 
    
    string infile;
 	ifstream infile;
 	infile.open("test.txt");
 	data.c_str();  
    infile>>data;
 	cout << data << endl;
   
   //  read the data from the file and display it.
   infile >> data; 
   cout << data << endl; 

   // close the opened file.
   infile.close();
 	
return 0;
 }
 
Last edited on
Well first of all you have:
1
2
 string infile;
 ifstream infile;

named the same thing, which you can't do, you'll have to name one of them something different. I assume you had the string named data based on what you have here: data.c_str(); but calling c_str(); without assigning it to anything wouldn't make sense as it returns a pointer to an array containing data of the string ( http://www.cplusplus.com/reference/string/string/c_str/ ). Also you don't even need to call c_str(); anywhere here because you aren't doing anything that would require a c string.

Also you need to #include <string> and then what you have should work, just note that infile>>data; will read only one word at a time
Last edited on
Topic archived. No new replies allowed.