1、cin

cin读取时,遇到空格、制表符、回车会立即终止输入

代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string s;
    cin >> s;
    cout << s << endl;
    return 0;
}

输出:

 

使用cin进行输入时,想要输入多个字符串,可以使用while

代码:

#include <iostream>
#include <string>
using namespace std;

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

输出:

2、getline()

 getline()读取一行字符串,通过回车键来确定输入的结尾

代码:

#include <iostream>
#include <string>
using namespace std;

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

输出:

3、cin.get()

 读取一个字符

代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char ch;
    ch=cin.get();
    cout << ch << endl;
    char sh;
    cin.get(sh);
    cout<<sh<<endl;
    return 0;
}

输出:

读取多个字符,可读取空格,最后会自动保存一个'\0'

代码:

#include <iostream>
using namespace std;

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

输出:

4、cin.getline()

接收一串字符,可以读取空格,最后默认添加'\0'

代码:

#include <iostream>
using namespace std;

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

输出:

5、gets()

 接收一串字符,可以读取空格,但是,gets()函数在读取字符串时,可以超过字符数组的容量

代码:

#include <iostream>
#include <string>
using namespace std;

int main()
{
    char ch[5];
    gets(ch);
    cout << ch << endl;
    return 0;
}

输出:

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐