C ++问题-getline跳过第一个输入 [英] C++ Issue - getline skips first input

查看:88
本文介绍了C ++问题-getline跳过第一个输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是使用 getline()的部分第一次不接受输入,只是说输入字符串:输入字符串:",然后您可以将输入内容放在此处

Tthe issue is that the part that uses getline() doesn't take input the first time, it just says "Enter a string: Enter a string:" and then you can put input there.

#include <iostream>
#include <string>

using namespace std;

int main()
{
  int nums[100], key=0, num = 0;

  while(num != -1)
  {
    cout << "Enter a positive integer (-1 to exit): ";
    cin >> num;

    if(num != -1)
    {
      nums[key] = num;
      key++;
    }

  }

    if(num != -1)
    {
      nums[key] = num;
      key++;
    }

    int numElements = key;
    string inStrings[100];

    for(int i=0; i < numElements; i++)
    {
      cout << "\n";
      cout << "Enter a string: ";
      getline(cin, inStrings[i]);
    }

    for(int i=0; i < numElements; i++)
    {
      cout << nums[i] << " :: " << inStrings[i];
    }

}

推荐答案

问题是您首先使用 cin>>num; 读取数字,但这会在 getline()调用读取的流中留下换行符.

The problem is that you first use cin >> num; to read a number, but that's leaving a newline in the stream which the getline() call reads.

也许在 cin>>之后添加 cin.ignore(1,'\ n'); num; 来吃那只流浪换行符.

Maybe add a cin.ignore(1,'\n'); after the cin >> num; to eat that stray newline.

这篇关于C ++问题-getline跳过第一个输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆