cin, getline, cin.getline, scanf, gets and other issues

1. When cin reads a number, for example cin>>s; we enter s and then press Enter to send s into the buffer, but cin does not read the newline character, so the newline character is not read. So when:

cin>>s;
getline(cin, str);

enter

2
string

getline will not read string, because getline can read newline characters. So the output result seems to be that getline has not been read.

2.getline(cin,str,a) reads str into the cin stream. When a is not written, it will stop inputting when it encounters a newline character by default and discards the newline character. If a is written, such as a is '#' It means stopping reading when encountering '#'.
For the while(getline(cin,line)) statement, note that the default carriage return character here stops reading. Press Ctrl+Z or type EOF and carriage return to exit the loop. In this statement, getline first reads characters from the standard input device, and then returns them to the input stream cin. Note that it is cin, so the real judgment object of the while judgment statement is cin, which is to judge whether there is currently a valid input stream. . Reference blog: https://blog.csdn.net/duan19920101/article/details/50782816

3. cin.getline reads the newline character and replaces it with '\0', and does not actively discard the newline character but leaves it in the input queue. Reference blog: https://blog.csdn.net/qq_38665104/article/details/82179096

4.scanf: will not read spaces, tabs, or newlines, and will end the input when encountering these.
gets: Can read spaces, tabs, and newlines.
Both will add '\0' at the end after reading the string.
Reference blog: https://www.cnblogs.com/wanghetao/archive/2011/11/01/2232234.html

Guess you like

Origin blog.csdn.net/weixin_45486992/article/details/120189149