您的位置:首页 > 编程语言 > C语言/C++

C/C++ 读入一行字符串

2016-04-03 12:12 351 查看

C/C++ 读入一行字符串

标签(空格分隔): 常用代码积累

1.gets

gets函数的头文件是

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int size = 1024;
char* buff = (char*)malloc(size);

// read lines
while(NULL != gets(buff)){
printf("Read line with len: %d\n", strlen(buff));
printf("%s", buff);
}

// free buff
free(buff);
}


2. fgets

fgets函数的头文件是

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
int size = 1024;
char* buff = (char*)malloc(size);

// read lines
while(NULL != fgets(buff, size, stdin)){
printf("Read line with len: %d\n", strlen(buff));
printf("%s", buff);
}
// free buff
free(buff);
}


**需要注意的是fgets保留换行符’\n’,而gets是从stdin输入,在读取字符串时会删除结尾的换行符’\n’;

同样,fputs写入时不包括换行符,而puts在写入字符串时会在末尾添加一个换行符。**

3. getline

对于C++语言,如果使用C字符串的话,就采用cin.getline()函数,如果采用string型字符串的话,就采用全局函数getline(cin,n);

注意,这两个函数都不读入最后的换行符

#include<string>
#include<iostream>
using namespace std;
int main( )
{
string s;
char str[256];
getline(cin, s);
cin.getline(str, sizeof(str));
return 0;
}


参考:/article/4753538.html

非常值得看的博客

/content/3670886.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: