1: write a program to read numbers from a file.
2: Write a program to read string from a file.
//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.
}
}
Comments
Leave a comment