About how to use cin.ignore() and <istream>

Asked 1 years ago, Updated 1 years ago, 39 views

Using C++, we are creating a program that inputs names in English from the console and prints English initials.

I made it as follows and it worked, but I would appreciate it if you could ask me the following two questions.

I would appreciate it if you could tell me how to use cin.ignore().
(How should I use it and what arguments should I specify?)

What kind of library is <istream>?

Do you need <istream> and <iomanip> for this program?

I searched Google for the answer above, but I was not sure, so I would appreciate it if you could let me know.

#include<iostream>
# include <string>
# include <istream>
// # include <iomanip>

using namespace std;
int main(void){

char firstInitial;
char lastInitial;

cout<<"Enter your first and last name:";

firstInitial=cin.get();

cin.ignore(256, ');

lastInitial=cin.get();

cout<<firstInitial<<lastInitial;

return 0;
}

Run Results
Enter your first and last name: Harry Truman

HT

c++

2022-09-30 21:30

1 Answers

A1.https://cpprefjp.github.io/reference/istream/basic_istream/ignore.html
In short, you skip "number of characters" or "until a particular character appears (including the first time of that particular character)."
In the presentation example, 256 characters or until a space appears (the first of the spaces is read).You can see the difference if you specify about 2 instead of 256.Alternatively, you can enter Harry Truman (enter two separate spaces).

A2.https://cpprefjp.github.io/reference/istream.html
<istream> means to use the function for "stream input".
In this example, cin is required because it uses a standard input stream (see answer below).

A3.https://cpprefjp.github.io/reference/iostream.html
<iostream> (as noted on the link) indicates that you have <ios><streambuf><ostream> all are include>.It's convenient because you can specify the functions that you often use at once, but unnecessary functions may also be compiled at the same time.#include<iostream> in the presentation example, so a new #include<istream> is not required.

https://cpprefjp.github.io/reference/iomanip.html
<iomanip> is required to use the manipulator (to do formatted input/output).The example does not have formatted input/output, so it works without it.

https://cpprefjp.github.io/reference/ostream.html
endl is also a manipulator, but it is defined by <ostream> instead of <iomanip> due to differences in usage.

functions and classes may be difficult to understand at first.
I'm looking for istream, but only basic_istream hits.
When you understand better, you will understand that it's actually the same thing.


2022-09-30 21:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.