C ++ character input function getline, cin.getline distinction

1. cin >> s; s can be: string s, char s [];

This is a function in ostream, it will automatically end when it encounters '' (space), '\ n' (line feed), so if you use cin to read a string, then this string cannot contain spaces and line feeds.

cin does not recognize spaces and line breaks, so if you enter a space or line break at the beginning of a character when entering a string, it has no effect.

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;


int main()
{
    string s;
    int n;
    while(cin>>s)
    {
        cout<<s<<endl;
    }
}

2. getline (cin, s, '\ n'), s can only be string s

getline belongs to the character reading function of the string class. The third parameter of this function can not be written (getling (cin, s)). The third parameter defaults to '\ 0'. In this case, if you want to end a string Input, for some compilers (VC, VS), you must enter two newlines in succession.

For getline (cin, s, 'z'), can recognize spaces and newlines

For getline, as long as the cut-off character (third parameter) is set properly, multiple lines can be read

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;


int main()
{
    string s;
    int n;
    while(getline(cin , s , 'z'))
    {
        cout<<s<<endl;
    }
}

3. cin.getline (s, 100, '/ n') can only be char s [];

cin.getline belongs to ostream. It is similar to getline, except that it can only read char s [] types. Except for this point, it is the same as getline.



Published 190 original articles · 19 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/zengchenacmer/article/details/38079529