JunsungChoi
JunsungChoi

Reputation: 87

C++ input goes wrong

I'm solving uva problem and trying to input series of Strings. The problem is when I try to input Strings in While loop, first input goes fine. But after that, the first character of each string is ignored. so I used __fpurge() function and it worked well. but I cannot use that function in uva Online Judge site. how can I replace __fpurge function?

char crypt_text[MAXLEN]


 int main()
    {
        char alphabet['z'+1], cryptchar['z'+1]; 
        std::cin>>n;

    for(int i=0; i<n; i++)
        std::cin>> dictionary[i];
    while(1)
    {
        __fpurge(stdin);
        std::cin.getline(crypt_text,MAXLEN,'\n');
        if(cin.eof()) break;
        for(int i=0; i<'z'+1; i++)
        {
            alphabet[i] = '\0';
            cryptchar[i] = '\0';
        }

        if(!crypt_kicker(0,alphabet,cryptchar)) print_asterisk();
    }
    return 0;
}

Upvotes: 0

Views: 122

Answers (1)

Maikel
Maikel

Reputation: 1269

I think your problems lies in __fpurge

For input streams this discards any input read from the underlying object but not yet obtained via getc(3);

Maybe this resolves your problems. Here is a more C++-ish way of handling the input.

int main()
{
    int n;
    std::cin >> n;
    // declare dict, whatever it is
    for(int i = 0; i < n; i++)
        std::cin >> dictionary[i];

    const std::size_t len = 'z'+1;
    std::array<char, len> alphabet;
    std::array<char, len> cryptchar; 

    std::string crypt_text;
    while(std::getline(std::cin, crypt_text))
    {
        std::fill(std::begin(alphabet), std::end(alphabet), 0);
        std::fill(std::begin(cryptchar), std::end(cryptchar), 0);

        if(!crypt_kicker(0,alphabet,cryptchar))
            print_asterisk();
    }
}

I am not sure if you really want len = 'z'+1 instead of len = 'z'-'a'+1 (no ending '\0' needed with std::array)

Upvotes: 2

Related Questions