Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In C++ Problem description: Open a file named \"foo\" and print each word in the

ID: 3734580 • Letter: I

Question

In C++

Problem description: Open a file named "foo" and print each word in the file on a different line. For example, if the contents of the file is: the quick brown fox jumped the fence then your output should be:

the

quick

brown

fox

jumped

the

fence

First, write include and using statements

GIVEN:

const string FILE_NAME = "foo";

int main() {

ifstream fin;

string word;

Next, Open fin and associate it with the filename stored in the constant variable FILE_NAME. If the file fails to open, then return -1. Do not output any error statments

Next, write a loop that reads words from fin and prints them to the console, one per line

Explanation / Answer

below is the code written as per your requirement.

as ifstream open a file name using its constructor.

example ifstream fin(file_name);

condition provided whether the name is written in constructor or char array is passed. but we have file name in string so first we convert it into char array. after we pass it to constructor.

if file name with this name exists in the same folder where your c++ code file is then it opens the file and print the content of data word by word in next line else it return -1 if file doesn't exists with this name......

hope this helps you . find the code below

---------------------------------------------------------------------------------------

#include<iostream>
#include <bits/stdc++.h>
#include<fstream>
using namespace std;
const string FILE_NAME = "foo.txt";
int main()
{
char data[100];
int n = FILE_NAME.length();
char char_array[n+1];
string line;
strcpy(char_array, FILE_NAME.c_str());
ifstream fin;
fin.open(char_array,ios::in);
string word;
if(!fin)
{
cout<<"-1"<<endl;
return 0;
}
else{
while(!fin.eof())
{
fin>>word; //read single character from file
cout<<word<<endl;
}
}
}

---------------------------------------------------------------------------------------------------------