getline(cin,variable) не хочет правильно работать на С++?

StackOverflow https://stackoverflow.com/questions/2485284

  •  21-09-2019
  •  | 
  •  

Вопрос

Вот моя программа на данный момент:

int main()
{
    char choice = 'D';
    string inputString;

    cout << "Please input a string." << endl;

    getline(cin, inputString);

    LetterCount letterCount(inputString);

    while(choice != 'E')
    {
        cout << "Please choose from the following: " << endl
            << "A) Count the number of vowels in the string." << endl
            << "B) Count the number of consonants in the string." << endl
            << "C) Count both the vowels and consonants in the string." << endl
            << "D) Enter another string." << endl << "E) Exit the program." << endl;

        cin >> choice;

        if(choice == 'A' || choice == 'a')
        {
            cout << "There are " << letterCount.vowelCount() << " vowels in this string." << endl;
        }
        else if(choice == 'B' || choice == 'b')
        {
            cout << "There are " << letterCount.consonantCount() << " consonants in this string." << endl;
        }
        else if(choice == 'C' || choice == 'c')
        {
            cout << "There are " << letterCount.vowelCount() << " vowels and " << letterCount.consonantCount()
                << " consonants in this string, for a total of " << (letterCount.vowelCount() + letterCount.consonantCount())
                << " letters." << endl;
        }
        else if(choice == 'D' || choice == 'd')
        {
            cout << "Please type in another string." << endl;

            getline(cin, inputString);

            letterCount.setInputString(inputString);
        }
        else
        {
            choice = 'E';
        }
    }
}

Я включаю только основной, поскольку он является источником проблемы, все остальное работает правильно.

Проблема возникает, когда я использую выбор «D» (ввожу новую строку). Как только нажимается Enter, программа возвращается прямо к подсказке выбора и устанавливает для переменной inputString пустое значение (не пустое слово, но ничего в нем). )

первый getline(cin, inputString) работает отлично, второй - источник проблемы... есть какие-нибудь предложения?

Это было полезно?

Решение

Я думаю, вам нужно добавить что-то вроде этого:std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');после твоего cin >> choice

Причина этого в том, что пользователь фактически ввел «D », но только «D» помещается в переменную выбора, поэтому « » попадает в буфер cin.когда вы вызываете getline, getline видит в буфере этот ' ' и возвращается ни с чем...

этот вызов выше удалит все ' ', которые находятся в буфере cin.

Это довольно хорошо объяснено здесь

другое решение было бы примерно таким:

char newline;
cin >> choice;
cin.get(newline);

Это удалит из буфера только один символ ' '.(с cin >> choice добавил один \n)

Другие советы

Не лучше ли вам использовать чехол-переключатель, такой как этот?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Initialize
void newString();
void menu();
void switchCases(choice);

//Variables
string inputString;
char choice;
LetterCount letterCount(inputString);


int main(){
    menu();
}

void newString(){
    cout << "Please type in another string." << endl;
    getline(cin, inputString);
    letterCount.setInputString(inputString);
}

void menu(){
    cout << "Please choose from the following: " << endl
    << "A) Count the number of vowels in the string." << endl
    << "B) Count the number of consonants in the string." << endl
    << "C) Count both the vowels and consonants in the string." << endl
    << "D) Enter another string." << endl << "E) Exit the program." << endl;
    cin >> choice;
        newString();
}



void switchCases(char choice){
    switch (choice){
        case 'A':
        case 'a':{
            cout << "There are " << letterCount.vowelCount() << " vowels in this string." << endl;
            break;}
        case 'B':
        case 'b':{
            cout << "There are " << letterCount.consonantCount() << " consonants in this string." << endl;
            break;}
        case 'C':
        case 'c':{
            cout << "There are " << letterCount.vowelCount() << " vowels and " << letterCount.consonantCount()
            << " consonants in this string, for a total of " << (letterCount.vowelCount() + letterCount.consonantCount())
            << " letters." << endl;
            break;}
        case 'Q':
        case 'q':{
            break;}
        default:
        case 'D':
        case 'd':{
            main();}
    }
}

Вы не совсем правильно используете getline.Попробуйте использовать такой скелет...

#include <iostream>
#include <iomanip>
#include <string>

using std::getline;
using std::string;
using std::cin;
using std::cout;
using std::endl;


const string instructions = "Please choose from the following:\nA) Count the number of vowels in the string.\nB) Count the number of consonants in the string.\nC) Count both the vowels and consonants in the string.\nD) Enter another string.\nE) Exit the program.\n";

int main()
{
    // print instructions
    cout << instructions;

    // input text
    string text;

    bool processing = true;

    // start loop
    while (processing && getline(cin, text) && !text.empty())
    {
        // switch on input character
        switch (text[0])
        {
            case 'A':
            case 'a':
            {
                cout << "Doin A stuff" << endl;;
                break;
            }
            case 'B': 
            case 'b':
            {
                cout << "Doin B stuff" << endl;;
                break;
            }
            case 'C': 
            case 'c':
            {
                cout << "Doin C stuff" << endl;;
                break;
            }   
            case 'D': 
            case 'd':
            {
                cout << "Doin D stuff" << endl;;
                break;
            }
            case 'E':
            case 'e':
            {
                cout << "Exiting..." << endl;;
                processing = false;
                continue;
                break;
            }
            default:
            {
                cout << "I have no idea what you entered" << endl;
                processing = false;
                continue;
                break;
            }
        }   


        // print instructions for next loop
        cout << endl << instructions;
    }

    return 0;
} 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top