vendredi 31 juillet 2020

Strange things with c++ string input

#include <iostream>
#include <cstring>
using namespace std;

const int BUFFER_SIZE = 80;

void getstr(char* &str);    

int main()
{
    char* str;
    while(true)
    {
        getstr(str);
        if (!strlen(str))
            break;
    }
    delete [] str;
    return 0;
}

void getstr(char* &str)
{
    char temp[BUFFER_SIZE];
    cout<<"Enter a string(empty line to quit): ";
    cin.get(temp, BUFFER_SIZE);
    while(cin.get()!='\n')
        continue;
    str = new char [strlen(temp)+1];
    strcpy(str, temp);
}

I have string reading loop above and entering empty line to terminate loop doesn't work(after entering empty line program stops responding to any input). But when I replace a loop in getstr with single cin.get() all works fine. What's wrong?

Aucun commentaire:

Enregistrer un commentaire