关于getline(cin,string)的C++快速问题



我已经有一段时间没有编写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;
}

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

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

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

最后,也是重要的一点是,如果输入整数的字母字符而不是…,您的程序将运行一个无限循环。。。整数。要缓解这种情况,请使用<cctype>库中的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();

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 

最新更新