关于C++中字符串的输入

在C++中字符串的输入主要有以下6种:

1.cin

2.cin.get()

3.cin.getline()

4.getline()

5.gets()

6.getchar()

前四种是C++里特有的,后两种是C++继承了C里的。

1.cin输入字符串时不会读取空格,遇到回车停止读入。用法就不举例了。

2.cin.get()方法:有三种形式( cin.get(char*string,m) , cin.get() ,cin.get(ch))

#include<iostream>
using namespace std;
int main(){
    char a[20];
    char c;
    cin.get(a,5);
    cout<<a<<endl;
    return 0;

}

3.cin.getline():读取一串字符串,并以指定的结束符结束

格式:cin.getline(char* s, streamsize count, char ch)最后一个参数可以缺省,缺省情况下是'\n’

#include<iostream>
using namespace std;
int main(){
    char s[20] ;
    cin.getline(s,5);
    cout<<s<<endl;
    return 0;

}

4.getline():注意是string类专用

#include<iostream>
using namespace std;
int main(){
   string String;
   getline(cin,String);
   cout<<String<<endl;
   return 0;

}

接下来介绍的是两种来自C语言的输入字符串方法,需要加入头文件cstdio(stdio.h也可以,但是最好是用cstdio)

5.gets():

gets可以接收空格,遇到回车认为输入结束;

gets 可接受回车键之前输入的所有字符,并用’\n’替代 ‘\0’。回车键不会留在输入缓冲区中。

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
   char a[20];
   gets(a);
   cout<<a<<endl;
   return 0;

}

6.getchar(): getchar()函数只能接受单个字符

#include<iostream>

#include<cstdio>

using namespace std;
int main(){
    char a;
    a =  getchar();
    cout<<a<<endl;
    return 0;
}








猜你喜欢

转载自blog.csdn.net/igoforward/article/details/80094576