简体   繁体   English

使用fstream在c ++中读取文件时显示额外的字符串

[英]showing an extra string while reading a file in c++ using fstream

I have a program in c++ which is used to read some text from a .txt file using fstream functions. 我有一个c ++程序,用于使用fstream函数从.txt文件中读取一些文本。 But on output screen, it is showing an extra output of while loop which is undesirable.So if tt.txt contains the data 但是在输出屏幕上,它显示了while循环的额外输出,这是不希望的。因此,如果tt.txt包含数据

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

See the C++ FAQ for help with I/O: http://www.parashift.com/c++-faq/input-output.html 有关I / O的帮助,请参见C ++常见问题解答: 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM