【问题标题】:C++ quick issue on getline(cin, string)关于 getline(cin, string) 的 C++ 快速问题
【发布时间】:2012-03-30 03:40:44
【问题描述】:

自从我编写 C++ 代码以来已经有一段时间了,我忘记了在收集字符串输入时发生的一件烦人的事情。基本上,如果这循环回来,比如说如果你使用负数,那么它会在第二轮跳过员工姓名行中的 cin。我记得之前遇到过这个问题,并且必须在输入字符串之前或之后清除或执行此类操作。请帮忙!

PS 另外,任何人都可以帮助我在下面的正确循环中获得额外帮助。如何检查字符串输入中的值以确保它们输入了值?

#include <string>
#include <iostream>
#include "employee.h"

using namespace std;

int main(){

    string name;
    int number;
    int hiredate;

    do{

        cout << "Please enter employee name: ";
        getline(cin, name);
        cout << "Please enter employee number: ";
        cin >> number;
        cout << "Please enter hire date: ";
        cin >> hiredate;

    }while( number <= 0 && hiredate <= 0 && name != "");

    cout << name << "\n";
    cout << number << "\n";
    cout << hiredate << "\n";

    system("pause");
    return 0;
}

【问题讨论】:

  • 您只想在名称为"" 时停止循环?我想你想要name == ""?我想你也想使用 or (||) 而不是 and (&amp;&amp;)

标签: c++ string


【解决方案1】:

您想将循环条件更改为是否未设置以下任何一项。只有当所有 三个 都未设置时,逻辑 AND 才会触发。

do {
    ...
} while( number <= 0 || hiredate <= 0 || name == "");

接下来,按照@vidit 的规定使用cin.ignore() 来解决读取换行符的问题。

最后,也是重要的一点,如果您输入一个字母字符作为整数而不是...整数,您的程序将运行一个无限循环。为了缓解这种情况,请使用 &lt;cctype&gt; 库中的 isdigit(ch)

 cout << "Please enter employee number: ";
 cin >> number;
 if(!isdigit(number)) {
    break; // Or handle this issue another way.  This gets out of the loop entirely.
 }
 cin.ignore();

【讨论】:

    【解决方案2】:

    cin 在流中留下一个换行符 (\n),这会导致下一个 cin 使用它。有很多方法可以解决这个问题。这是一种方式.. 使用ignore()

    cout << "Please enter employee name: ";
    getline(cin, name);
    cout << "Please enter employee number: ";
    cin >> number;
    cin.ignore();           //Ignores a newline character
    cout << "Please enter hire date: ";
    cin >> hiredate;
    cin.ignore()            //Ignores a newline character 
    

    【讨论】:

    • 很好,但是如果你输入一个字符而不是一个整数作为数字,它并不能解决问题,如果你没有输入一个名字,它也不能解决循环。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-04-25
    • 2013-09-23
    • 1970-01-01
    • 2014-06-22
    相关资源
    最近更新 更多