繁体   English   中英

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

[英]C++ quick issue on getline(cin, string)

它已经有一段时间了,因为我已经编码了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;
}

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 

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

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

接下来,使用cin.ignore()规定的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM