C/C++的各种标准输入字符串方法
一些前置知识
字符串有两种形式。一种是C语言风格的C字符串,C字符串是以字符 ‘\0’ 结尾的字符数组;一种是C++中的string类,声明在<string>中。
C语言的IO函数声明在<stdio.h>(在C++环境下也可写作 <cstdio>)中。有scanf、printf;gets/fgets、gets。
C++的输入函数声明在<iostream>中。有cin、cout;cin.getline();cin.get();getline()。
C语言的IO函数输入、输出字符串
scanf和printf
首先看一下两个函数的声明。
int scanf ( const char * format, ... );
int printf ( const char * format, ... );
scanf遇见空格、制表符、换行符就会分割字符串,所以它无法输入带有空格的字符串。
#include <cstdio>
int main() {
chat str[20];
scanf("%s", str); // input: c and cpp
printf("%s\n", str); // output: c
return 0;
}
gets、fgets和puts
C语言如何获得带有空格的字符串呢?
使用gets获得一个带有空格的句子。gets在遇到换行符或文件结尾时停止读取输入。
char * gets ( char * str );
char * fgets ( char * str, int num, FILE * stream );
int puts ( const char * str );
gets会产生一个警告,可以用fgets函数替代gets。
#include <cstdio>
int main() {
char str[20];
gets(str);
//fgets(str, 20, stdin); // If the length of input string is greater than 20,
//it can only store first 19 characters in str.
puts(str);
return 0;
}
C++的IO函数输入、输出字符串
cin和cout
cin与scanf一样也是遇见空格、制表符、换行符就会分割字符串,所以它无法输入带有空格的字符串。
#include <iostream>
using namespace std;
int main() {
chat str[20];
cin>>str; // input: c and cpp
cout<<str; // output: c
return 0;
}
cin.getline()、cin.get()
cin.getline()与cin.get()都能接收输入的带有空格的字符串直到遇到换行符停止接收。
但是二者稍有区别:cin.getline()丢弃换行符,而cin.get()将其保留在输入队列中。
下面两段代码通过cin.get()与cin.getline()不同的调用顺序做一个对比,可以看出cin.getline()与cin.get()的区别。
在第一段代码中,cin.get()将其保留在输入队列中,cin.getline()会先捕获上次输入的最后的换行符,捕获后cin.getline()结束,终端也不会继续让用户输入。
#include <iostream>
using namespace std;
int main() {
char str[20];
cout<<"Enter a string by cin.get():";
cin.get(str, 20); // input: C and C++
cout<<"received by cin.get():"<<str<<endl;
cout<<"Enter a string by cin.getline():";
cin.getline(str, 20);
cout<<"received by cin.getline():"<<str<<endl;
return 0;
}
运行结果如下:
在第二段代码中,cin.getline()丢弃输入的最后的换行符,cin.get()则可仍然接收用户输入。
#include <iostream>
using namespace std;
int main() {
char str[20];
cout<<"Enter a string by cin.get():";
cin.getline(str, 20); // input: C and C++
cout<<"received by cin.get():"<<str<<endl;
cout<<"Enter a string by cin.getline():";
cin.get(str, 20); // input: C and C++
cout<<"received by cin.getline():"<<str<<endl;
return 0;
}
运行结果如下:
留在输入队列中换行符的处理方法
可以调用一次cin.get()去吸收换行符
#include <iostream>
using namespace std;
int main() {
char str[20];
cout<<"Enter a string by cin.get():";
cin.get(str, 20); // input: C and C++
cout<<"received by cin.get():"<<str<<endl;
cin.get();
cout<<"Enter a string by cin.getline():";
cin.getline(str, 20);
cout<<"received by cin.getline():"<<str<<endl;
return 0;
}
运行结果如下:
getline()接收string类对象
前面介绍的几种函数都是处理C风格字符串的,注意:getline()与cin.getline()不是一个函数。
#include <iostream>
using namespace std;
int main ()
{
string str;
getline(cin,str); // input: c and cpp
cout<<str; // output: c
return 0;
}