字符串输入
gets():
feature:
- 从stdio流中读取 字符串,直至接受到换行符或EOF时停止,换行符不作为读取串的内容,读取的换行符被转换为‘\0’空字符,并由此来结束字符串。结束时,不会在缓冲区中留下换行符。
- 可以接受空格符和制表符,不可接受换行符(会自动转化为\n)
- 会自动在末尾补上’\0’(由换行符转化)
- 不安全,在部分编译器中被弃用
example:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[10];
gets(a);
for(int i=0;i<strlen(a);++i){
cout<<i<<":"<<(int)a[i]<<endl;
}
return 0;
}
scanf():
feature():
- 遇见空格、回车、制表符停止,会读取空格、回车、制表符前面的内容,将这三个字符留在缓冲区。
- 会自动在末尾补上’\0’
- 若空格、回车、制表符为首字符,则会读取后丢弃这三个字符,见example1
- 利用上面的机制,可以连续读取多个字符串,见example2
- 若遇到gets()无法使用,且有读取空格的需求时,可以使用scanf("%[^\n]", str)。
example1:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[10];
scanf("%s",a);
for(int i=0;i<strlen(a);++i){
cout<<i<<":"<<(int)a[i]<<endl;
}
char b;
while(b = getchar()){
cout<<(int)b<<endl;
}
return 0;
}
example2:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
char a[10];
char b[10];
scanf("%s%s",a,b);
for(int i=0;i<strlen(a);++i){
cout<<i<<":"<<(int)a[i]<<endl;
}
for(int i=0;i<strlen(b);++i){
cout<<i<<":"<<(int)b[i]<<endl;
}
return 0;
}
cin:
feature:
- 与scanf()一致
getline(c++):
feature:
- 由两种使用方法:
- 方法一:istream &getline( char *buffer, streamsize num, char delim );
- 方法二:istream &getline( char *buffer, streamsize num );
- 方法一中的delim为结束符,getline读取到delim时结束输入,并且会将delim丢弃,不会在缓冲区中留下delim结束符
- 方法二中的delim默认为’\n’,这种使用方法和gets()比较相似,唯独不会留下换行符在缓冲区中
- 在c++中,string类不需要在尾部加上’\0’,他有自己的类成员方法可以保存string变量的长度,但是实际测试中,getline()仍会在尾部加上’\0’
example1:
code:
#include<iostream>
#include<string.h>
using namespace std;
int main(){
string s;
s[1] = 'a';
getline(cin,s);
for(int i=0;i<s.length();++i){
cout<<i<<":"<<(int)s[i]<<endl;
}
char a;
cout<<"end:"<<(int)s[s.length()]<<endl;
while(a = getchar()){
cout<<(int)a<<endl;
}
}
input:
a[回车]
output:
0:97
end:0
字符串输出
char数组
puts(s);
feature:
- 输出第一个字符到’\0’之间的所有字符
- 会自动换行
printf("%s",s);
feature:
- 输出第一个字符到’\0’之间的所有字符
cout>>s;
feature:
- 输出第一个字符到’\0’之间的所有字符