Мои операторы getline и cout в моем цикле for усекаются

Для этого кода он запрашивает первую песню, сохраняет и распечатывает ее. Но после первой записи меня спрашивают, хочу ли я продолжать, как я хотел, но затем, после того, как я набираю Y, он пропускает мой вопрос о песне и функцию getline и сразу спрашивает, хочу ли я продолжать или нет, что я здесь делаю неправильно?

это мой результат

Введите название песни. Мне нужна помощь
Продолжить (да/нет)? y
Введите название песни. Вы хотите продолжить (т/н)? y
Введите название песни. Вы хотите продолжить (т/н)? y
Введите название песни. Вы хотите продолжить (т/н)? n
Было введено 4 названия песен.
Мне нужна помощь

Где мой желаемый результат и ожидаемый результат

Введите название песни. Мне нужна помощь
Продолжить (да/нет)? y
Введите название песни. Печать
Продолжить (да/нет)? y
Введите название песни. И ввод
Продолжить (y/n)? y
Введите название песни. Эти песни
Продолжить (да/нет)? n
Было введено 4 названия песен.
Мне нужна помощь
Печать
И ввод
Эти песни

/*This program will ask a user to enter a song list. By doing this each time that the     user enters
a song, he/she will then be asked if they want to enter another song, if yes then they     will enter another song.There will be a maximum of 15 songs.
This progarm will help a user keep track of their songs. But then the program will     output the amount of songs, and what they are.
input:A song. Then a yes or no, if yes, another song, if no the program will output.
output:The number of songs, and then the songs themselves, each song with it's own     individual line.
processing: There will be two functions, one of which will ask the user for the songs and     store them, and another for which will be computing
the output.
*/
    #include<iostream>
    #include<string>

using namespace std;

int input(string[15], int);
void printArray(string[15], int);

int main()
{
    const int arraysize=15;
    string songarray[arraysize];

     int x=input(songarray, arraysize);



      cout<<"There were "<<x<<" song titles entered.\n";
      printArray(songarray, x);
       return 0;
       }

/*This function will ask for the users input for a song and store the song in the     songarray. He or she
will then be asked whether or not they want to enter another song, if so, then they     will enter another song.
input:a song, y/Y or n/N for if they want to continue or not with another song
output:song will be sent to main function
processing: A while loop will be used for the user to enter is Y or N, and a for loop     (while loop nested) for the user to enter the 
songs
*/
int input(string titles[15], int rows)
{

      char answer='y';
      int k=0;
      for(int i=0;i<rows && (answer=='Y' || answer=='y');i++)
      {

           cout<<"Enter the name of a song. ";
           getline(cin, titles[i]);
           cout<<"Do you want to continue (y/n)? ";
           cin>>answer;
           k=i+1;
            }
           return k;
           }

/*The purpose of this function is to print the array from the main function.
input:accepts the array from the main function
output: prints the array
processing:nested loops will pring this array.
*/

void printArray(string playlist[15], int quantity)
{
    for(int j=0; j<quantity; j++)
    {
        cout<<playlist[j];
    }
}

person M. Elliot Frost    schedule 19.04.2011    source источник
comment
Это домашнее задание? Это нормально, если это так, но мы хотели бы знать.   -  person John Dibling    schedule 19.04.2011
comment
попробуйте использовать cin >> titles[i] вместо getline   -  person Elalfer    schedule 19.04.2011


Ответы (3)


Проблема в том, что ваш «cin >> answer» читает один символ, но вы вводите «y», а затем нажимаете ввод, поэтому символ новой строки все еще находится в cin. Поэтому, когда ваш цикл возвращается, getline просто читает этот символ новой строки, и вы получаете пустую строку.

Если вы сделаете:

string dummy;
getline(cin, dummy);

после «cin>>answer» он съест этот завершающий символ новой строки.

person finsprings    schedule 19.04.2011
comment
это полностью сработало, в этом так много смысла, потому что я смотрел на код и думал, что это не может быть случайным пропуском моего оператора cout, он должен принимать другой символ или что-то в этом роде. А теперь понятно, спасибо1 - person M. Elliot Frost; 19.04.2011

char answer;
cin >> answer;

действительно проблема: посмотрите на cin.ignore для другого решения

person sehe    schedule 19.04.2011

char answer;
cin >> answer;

Какие клавиши вы нажали, чтобы ответить на вопрос программы? Какой из них оказался в answer? Какой из них остался на стандартном вводе, завершая следующую строку getline, прежде чем вы наберете что-нибудь еще?

person DevSolar    schedule 19.04.2011