Reputation: 39
I have a program in c++ which is used to read some text from a .txt file using fstream functions. But on output screen, it is showing an extra output of while loop which is undesirable.So if tt.txt contains the data
ss
123
then output is
Name ss
roll no 123
name
roll 123
Code:
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<string.h>
#include<stdio.h>
void student_read()
{
clrscr();
char name[30];
int i,roll_no;
ifstream fin("tt.txt",ios::in,ios::beg);
if(!fin)
{
cout<<"cannot open for read ";
return;
}
while(!fin.eof())
{
fin>>name;
cout<<endl;
fin>>roll_no;
cout<<endl;
cout<<"Name is"<<"\t"<<name<<endl;
cout<<"Roll No is"<<roll_no<< endl;
}
}
void main()
{
clrscr();
cout<<"Students details is"<<"\n";
student_read();
getch();
}
Upvotes: 0
Views: 460
Reputation: 1902
See the C++ FAQ for help with I/O: http://www.parashift.com/c++-faq/input-output.html
#include <iostream>
#include <fstream>
void student_read() {
char name[30];
int roll_no;
std::ifstream fin("tt.txt");
if (!fin) {
std::cout << "cannot open for read ";
return;
}
while(fin >> name >> roll_no) {
std::cout << "Name is\t" << name << std::endl;
std::cout << "Roll No is\t" << roll_no << std::endl;
}
}
int main() {
std::cout << "Students details is\n";
student_read();
}
Upvotes: 2