程序跳过getline

program skip over getline

本文关键字:getline 程序      更新时间:2023-10-16

我想创建一个程序,以便在输入'y'时,它将在第一个do-while循环中执行代码。但是,当输入'y'时,它只是跳过大量代码!

输入电话符号:

2

继续(y/y):y

输入电话符号:

继续(y/y):/blockquote>

无论如何,我可以在不使用cin.ignore的情况下解决此问题,因为它会更改布局。预先感谢!

#include <iostream>
#include <cstdlib>
#include <cctype>
#include <iomanip>
#include <cstring>
const int MAX = 100;
using namespace std;
int getInt(char);
bool isValidChar(char);
int main()
{
    int num;
    int j = 0;
    char name, conti;
    char alpha[MAX];
    do {
        cout << "Enter a phone symbols: " << endl;
        cin.getline(alpha, MAX);
        // cin.ignore(100, 'n');
        while (alpha[j] != '')
        {
            name = alpha[j];
            if (isValidChar(name) == true)
            {
                num = getInt(name);
                if (num == -1)
                {
                    cout << "-";
                }
                else
                {
                    cout << num;
                }
            }
            else
            {
                cout << " - Invalid Char " << name << " found - rejected";
            }
            j++;
        } // end while
        cout << endl;
        do {
            cout << "nContinue (Y/y): ";
            cin >> conti;
            cout << "n" << endl;
            conti = tolower(conti);
            if (conti == 'n')
            {
                exit(0);
            }
        } while (conti != 'n' && conti != 'y');
    } while (conti == 'y');
}
int getInt(char input)
{
    int result;
    char value;
    value = tolower(input);
    if ((value >= 'a' && value <= 'c'))
    {
        result = 2;
    }
    else if ((value >= 'd' && value <= 'f'))
    {
        result = 3;
    }
    else if ((value >= 'g' && value <= 'i'))
    {
        result = 4;
    }
    else if ((value >= 'j' && value <= 'l'))
    {
        result = 5;
    }
    else if ((value >= 'm' && value <= 'o'))
    {
        result = 6;
    }
    else if ((value >= 'p' && value <= 's'))
    {
        result = 7;
    }
    else if ((value >= 't' && value <= 'v'))
    {
        result = 8;
    }
    else if ((value >= 'w' && value <= 'z'))
    {
        result = 9;
    }
    else if (value == ' ')
    {
        result = -1;
    }
    return result;
}
bool isValidChar(char value)
{
    if (isalpha(value) || value == ' ')
    {
        return true;
    }
    else
    {
        return false;
    }
}

您的意思是:无论如何,我可以在不使用cin.ignore的情况下解决此问题。

您的布局是基本上由以下行所抑制的:

cout << "nContinue (Y/y): ";
cin >> conti;
cout << "n" << endl;   // <-- this one
conti = tolower(conti);

如果您将其放置,则不会有空线。否则,如果您将其更改为

cout << endl;

只有一条空线。