Answer to Question #208737 in C++ for bilal

Question #208737

1: write a program to read numbers from a file.

2: Write a program to read string from a file.


1
Expert's answer
2021-06-20T08:10:58-0400
//Reading integers from a file  
#include<iostream>
#include <fstream>
using namespace std;
int main() {
   //initializing the array size
   int array[40];
   ifstream file("student.txt");
   int count= 0;
   int y;
   //Validating if the array is not full
   while (count < array[30] && file >> y)
   // Reading an integer
   array[count++] = y;
   //Printing the numbers stored in the array. 
   cout<<"The numbers are:"<<"\n";
   for (int n = 0; n < count; n++) {
      cout << array[n] <<' ';
   }
   //close the file
   file.close();
}
//Creating a file , writing on it and reading the strings fro the file
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(){
   fstream file;
   file.open("student.txt",ios::out);  //Writing operation to insert data into the file
      if(file.is_open())     //Returning true if the file is open 
   {
      file<<"I love coding \n"; //inserting text
      file.close(); //closing the file after writing om it
   }
   file.open("student.txt",ios::in); //Opening a file to perform reading operation on
   if (file.is_open()){   //Returning true if the file is open
         string stu;
      while(getline(file, stu)){  
         cout << stu << "\n";   
      }
      file.close();   //closing the file after reading it.
   }
} 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS