C ++ character input

When you learn C ++ programming, it is generally used in terms of input cin. And cin is the use of white space (spaces, tabs, and line breaks) delimited string of. This has led to a string with spaces , such as "I Love www.CppLeyuan.com" read only "I", the latter can not be read. Then how to do? (Forum: www.cppleyuan.com )

 For a. Array of characters :  Method a: getline () reads the entire line, which line feed input end of the input to determine the Enter key. Calling the method: cin.getline (str, len); str The first parameter is the name used to store an array of input lines, the second parameter len is the number of characters to be read.

#include 
using namespace std;

int main()
{
    char str[30];
    cin.getline(str, 30);
    cout << str << endl;
    return 0;
}

Method two: get ()

Call the method: cin.get (str, len);

#include 
using namespace std;

int main()
{
    char str[30];
    cin.get(str, 30);
    cout << str << endl;
    return 0;
}

So what is the difference of both? Both read a line input until newline. Then, getline newline discarded, while the get () will be retained in the newline character in the input sequence . Therefore, reuse cin.get () input multiple rows of data, using the intermediate can get () to eliminate line breaks.

#include 
using namespace std;

int main()
{
    char str1[30], str2[30];
    cin.get(str1, 30);
    cin.get();
    cin.get(str2, 30);
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    return 0;
}

Because get (str, len) and get () are class members cin, it can be combined to write:

#include 
using namespace std;

int main()
{
    char str1[30], str2[30];
    cin.get(str1, 30).get();   // 注意这里!
    cin.get(str2, 30);
    cout << "str1: " << str1 << endl;
    cout << "str2: " << str2 << endl;
    return 0;
}

 

II.  For the string class  method: getline (cin, str)

This shows that getline is not a class method here.

#include 
#include 
using namespace std;

int main()
{
    string str;
    getline(cin, str);
    cout << str << endl;
    return 0;
}

Original Address: http://www.wutianqi.com/blog/1181.html 

发布了69 篇原创文章 · 获赞 28 · 访问量 3万+

Guess you like

Origin blog.csdn.net/qq_24852439/article/details/91399898