While循环接收第一和第二个cin的输入

时间:2019-03-20 11:18:15

标签: c++ while-loop cin

我对这些代码行的意图是创建一个程序,该程序将显示用户键入的短语有多少个字符。我用另一项任务完成了我的代码行,以创建提示用户结束程序或循环程序。为此,我创建了一个while循环。一切都进行得很顺利,直到提示我“再次执行?”。无论我键入什么输入,它都会自动为我的第一个输入提供输出,这意味着它也为我的第一个cin输入输入。供参考,这是我的代码:

items.map(...)

很抱歉,如果我的问题含糊或使用了错误的用语,那我才开始学习c ++。

谢谢。

2 个答案:

答案 0 :(得分:2)

您应在std::cin.ignore()之后添加cin>>again

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

int main()
{
char again = 'y';
string phrase;
while (again == 'y' || again == 'Y')
{

cout << "Enter your phrase to find out how many characters it is: ";
getline(cin,phrase);
cout << phrase.length() << endl;
cout << "Go again? (y/n) " ;

cin >> again;
cin.ignore();
}
cout << "The end." << endl;

system ("pause");
}

问题是在std::cin之后,新行仍将保留在输入缓冲区中,而getline()将读取该换行符。 std::ignore()只会从输入缓冲区中抓取一个字符并将其丢弃。

有关更多信息,请参见http://www.augustcouncil.com/~tgibson/tutorial/iotips.html#problems

答案 1 :(得分:2)

std::cin << varname有一些问题。

当用户在输入变量之后键入“ enter”时,cin将仅读取变量,而将“ enter”保留给下一次读取。

cingetline()混合在一起后,有时会吃掉“ enter”,有时却不吃。

一种解决方案是在ignore调用之后添加一个cin调用以吃掉'enter'

cin >> again;
std::cin.ignore();

第二种解决方案是使用std :: getline()。最好将getline()与std :: istringstream结合使用。这是使用getline()和istringstream解决此问题的替代方法。有关说明,请参见代码中的注释。

#include <iostream>
#include <string.h>
#include <sstream>

int main()
{
  std::string line;
  std::string input;
  std::istringstream instream;

  do {
    instream.clear(); // clear out old errors

    std::cout << "Enter your phrase to find out how many characters it is: "
              << std::endl;

    std::getline(std::cin, line);
    instream.str(line); // Use line as the source for istringstream object

    instream >> input;  // Note, if more than one word was entered, this will
                        // only get the first word

    if(instream.eof()) {
      std::cout << "Length of input word:  " << input.length() << std::endl;

    } else {
      std::cout << "Length of first inputted word:  " << input.length() << std::endl;

    }
    std::cout << "Go again? (y/n) " << std::endl;
  // The getline(std::cin, line) casts to bool when used in an `if` or `while` statement.
  // Here, getline() will return true for valid inputs. 
  // Then, using '&&', we can check
  // what was read to see if it was a "y" or "Y".
  // Note, that line is a string, so we use double quotes around the "y"
  }  while (getline(std::cin, line) && (line == "y" || line == "Y"));

  std::cout << "The end." << std::endl;

  std::cin >> input; // pause program until last input.
}
相关问题