user12067965
user12067965

Reputation:

Im learning c++, file handling. i came across a piece of code that i did not understand

What is the use of cin.get(ch); in the following code? Why and when should I use it and what is the problem if I don't use it.

This code is from c++ sumit arora computer science with C++ textbook. I am using Code Blocks for my C++ code.

#include<iostream>
#include<fstream.h>
using namespace std;
int main()
{
    ofstream fil;
    char name[80],ch;
    int age;
    fil.open("mytext.txt",ios::out);
    for(int i = 0;i < 5;++i)
    {
        cout<<"Enter your name";
        cin.get(name,80);
        cout<<"Enter your age";
        cin>>age;
        cin.get(ch);        // What is the purpose of this line?
        fil<<name<<"\n"<<age<<"\n";
    }
    fil.close();
    return 0;

}

Upvotes: 0

Views: 73

Answers (1)

eesiraed
eesiraed

Reputation: 4654

See the reference for std::istream::get. It's a weird way of ignoring the next character, which is most likely the line break after the inputted number. cin.get(ch) extracts the next character and puts it into ch, which is never used. It would make more sense to use cin.ignore() instead of extracting into a dummy variable.

Upvotes: 1

Related Questions