【问题标题】:Significance of get() in the C++ snippetC++ 代码片段中 get() 的意义
【发布时间】:2017-08-17 17:05:53
【问题描述】:

这是与file handling 相关的问题,我们将数据输入文件然后显示其内容。我无法理解cin.get(ch); 行如何帮助输出。我发现如果我从代码中删除这一行,程序将无法在第二次迭代中获取变量标记的输入。为什么会这样?我对get() 的工作有点困惑。我的代码:

 #include<iostream>
 #include<conio>
 #include<fstream>
 int main()
 {

  ofstream fout;
  fout.open("student",ios::out);
  char name[30],ch;
  float marks=0.0;
  for(int i=0;i<5;i++)
  {
   cout<<"Student "<<(i+1)<<":\t Name:";
   cin.get(name,30);
   cout<<"\t\t Marks: ";
   cin>>marks;
   cin.get(ch); **// the confusion is in this line**
   fout<<name<<"\n"<<marks<<"\n";
  }
  fout.close();
  ifstream fin;
  fin.open("student",ios::in);
  fin.seekg(0);
  cout<<"\n";
  for(i=0;i<5;i++)
  {
   fin.get(name,30);
   fin.get(ch);
   fin>>marks;
   fin.get(ch);
   cout<<"Student Name: "<<name;
   cout<<"\t Marks: "<<marks<<"\n";
  }
  fin.close();
  return 0;
}

【问题讨论】:

  • 也许可以在前一个输入之后读取输入缓冲区中的换行符?
  • 输入的样子如何?
  • 使用std::string,然后像往常一样从流中读取cin &gt;&gt; namecin.get(ch) 的目的到底是什么?请提供输入和预期输出。
  • @AndyG 这是他问题的一部分,他不明白为什么需要/使用cin.get(ch)/
  • 如果混合 cin.get() 和 cin >> 程序将跳过 cin.get 放置在 cin >> 之后。由于 cin.get()s 正在检测 '\n'。编辑:您需要将 cin.ignore() 添加到相关位置以使其工作。还可以了解 cin.get 是为了展示您的努力和进行研究。

标签: c++ file get file-handling read-write


【解决方案1】:

从功能描述来看

basic_istream<charT,traits>& get(char_type* s, streamsize n,
char_type delim );

在 C++ 标准中:

字符被提取和存储,直到发生以下任何情况: ...

— traits::eq(c, delim) 用于下一个可用的输入字符 c (in 哪种情况 c 未被提取)。

从函数的描述来看

basic_istream<charT,traits>& get(char_type* s, streamsize n);

效果:调用 get(s,n,widen('\n'))

因此调用

cin.get(ch); 

用于从输入缓冲区中提取换行符。否则下一次调用函数

cin.get(name,30);

将读取一个空字符串。

代替调用

cin.get(ch); 

你可以调用成员函数ignore

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-05
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多