0

我有一个 c++ 程序,用于使用 fstream 函数从 .txt 文件中读取一些文本。但是在输出屏幕上,它显示了一个额外的while循环输出,这是不受欢迎的。所以如果tt.txt包含数据

ss 
123

然后输出是

Name ss
roll no 123

name
roll 123

代码:

#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();
}
4

1 回答 1

2

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();
}
于 2013-10-10T12:32:23.013 回答