从c++11之后取消了gets()函数,用fgets()代替,用法有所不同,这里详细介绍下fgets()该如何使用。
char *fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
第一个参数为数据存放的数组,第二个参数为最大长度,第三个参数为输入源,我们从键盘读入,参数为stdin。
#include <stdio.h>
#include <cstring>
char A[20];
int main() {
fgets(A , 20, stdin);
int lengthA = strlen(A)-1;
printf("lenA:%d\n",lengthA);
printf("start: %c\n",A[0]);
printf("end: %c",A[lengthA-1]);
return 0;
}
可以看到fgets()读取的字符串长度包含了结尾的 ‘\0’,遍历数组时要注意下标越界。strlen(A)-1 为字符串实际长度。
如果要从指定位置存储字符串呢
可以给第一个参数指定开始存储的位置
#include <stdio.h>
#include <cstring>
char A[20];
int main() {
fgets(A+1 , 20, stdin);
int lengthA = strlen(A+1)-1;
printf("lenA:%d\n",lengthA);
printf("start: %c\n",A[1]);
printf("end: %c",A[lengthA]);
return 0;
}
我们从下标为1的位置插入长度为3的字符串asd,此时A[0]的位置为null 计算字符串长度也应该相应的从A+1开始,如strlen(A+1),否则会出错。
我们使用strlen(A)测试如下:
使用fgets(),相应的也要使用fputs()输出。
fputs (const char *__restrict __s, FILE *__restrict __stream)
第一个参数为输出的数组,第二个参数为输出方式。我们使用stdout输出到屏幕