【问题标题】:program skipping a line of code程序跳过一行代码
【发布时间】:2011-05-13 14:21:11
【问题描述】:

我已经在这个程序上工作了一段时间,我终于摆脱了编译错误。但是我一试,程序基本跳过了一行代码。

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int main(){
  string nameOfFile = "";
  char index;
  char title[100];
  char name[100];
  char copyright[100];

  cout << "Welcome, and hello to the html templating software" << endl;
  cout << "Is this your index page?\ny/n" << endl;

  cin >> index;
  if (index=='n'){
    cout << "Enter the prefered name of this file" << endl;
    getline(cin, nameOfFile, '\n');
  }

  cout << "What will the title of the page be?" << endl;
  cin.getline(title, 100);

  cout << "What is your name?" << endl;
  cin.getline(name, 100);

  cout << "What is the copyright?" << endl;
  cin.getline(copyright, 100);

  cin.get();
  return 0;
}

您会看到,在询问这是否是您的索引页面后,无论哪种情况,它都会跳过下一个 cin.getline 函数。

【问题讨论】:

    标签: c++ textinput skip


    【解决方案1】:

    当用户输入索引时,他们还输入了一个换行符,但您的 cin 没有从输入流中删除它。因此,由于剩余的换行符,您对 cin.getline 的调用会立即返回。

    在 cin.getline 之前添加对 cin.ignore 的调用以将其清除。

    【讨论】:

      【解决方案2】:

      替换 getline(cin, nameOfFile, '\n')

      cin >> nameOfFile

      【讨论】:

      • 我不能这样做我需要获得空间
      猜你喜欢
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      • 2016-02-03
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多