while循环输入第一个和第二个cin

问题描述 投票:1回答:2

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

#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;

}
cout << "The end." << endl;

system ("pause");
}

对不起,如果我的问题含糊不清或我使用了错误的术语,我刚开始学习c ++。

谢谢。

c++ while-loop cin
2个回答
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


2
投票

std::cin << varname存在一些问题。

当用户在输入变量之后键入'enter'时,cin将只读取变量,并将为下次读取留下'enter'。

当你把cingetline()混合在一起时,你有时会吃'enter'而有时不吃'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.
}
© www.soinside.com 2019 - 2024. All rights reserved.