How do I derive an output other than \"Something wrong while opening the file.\"
ID: 3601784 • Letter: H
Question
How do I derive an output other than "Something wrong while opening the file." The program run successful, but always defaults to that closing cout. I don't quite understand where the loop could have gone. Can you explain for me, please? //Using a file test #includec iostream» #include #include using namespace std; int mainO string each_line; //Opening a file in read mode ifstream infile("testfile"); //Checking if file opened successfully if (infile.is_open()) //Reading in line from input file while (infile >> each_line) //Dislaying each line read coutExplanation / Answer
I think the file might be missing from the working directory. I typed the above code in Codeblocks and got the error "Something wrong while opening the file".
Then I created the file and entered the contents, and run it again, then I got it to work and I got the output. The ide you are using might have configurations to read the file, from a particular place, or the file might be missing. I am attaching my code, the testfile, the output and the directory structure as image.
****************************************************************************
Code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string each_line;
ifstream infile("testfile");
if(infile.is_open()){
while(infile >> each_line)
cout << endl << each_line;
infile.close();
}
else{
cout << endl << "Something wrong while opening the file" << endl;
}
}
****************************************************************************
Output:
I
am
from
test
file.
Please
print
me.
Process returned 0 (0x0) execution time : 0.031 s
Press any key to continue.
****************************************************************************
testfile
I am from test file.
Please print me.
****************************************************************************
Directory structure:
****************************************************************************
I hope this helps you.
If you find my answer helpful,
Kindly rate the answer.
All the best :)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.