I am writing a code but when I try to open the file it prints one word per line
ID: 3685462 • Letter: I
Question
I am writing a code but when I try to open the file it prints one word per line ....how can I make it print lines and not just words (preferably using getline, and needs to be using dev c++)
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
string line;
cout<<"Enter file name: ";
cin>> filename;
inputFile.open(filename.c_str());
if(!inputFile.is_open()){
cout << "open failed ";
return 1;
}
while (inputFile>> line ){
cout<< line <<endl;
}
inputFile.close();
system ("PAUSE");
return 0;
}
Explanation / Answer
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main()
{
ifstream inputFile;
string filename;
string line;
cout<< "Enter file name: ";
cin >> filename;
inputFile.open(filename.c_str());
if(!inputFile.is_open())
{
cout << "open failed ";
return 1;
}
while (getline(inputFile,line)) // reading line by line
{
cout<< line << endl; // output line
}
inputFile.close();
system ("PAUSE");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.