网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

c读取一行字符串,以及c++读取一行字符串的实例

一 c读取一行字符串

目前创新互联已为近1000家的企业提供了网站建设、域名、虚拟空间、绵阳服务器托管、企业网站设计、九原网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

1 gets

#include  
#include  
#include  

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); 
} 

利用getchar()读取一个个字符来读取一行

#include  
#include  

int my_getline(char* line, int max_size) 
{ 
 int c; 
 int len = 0; 
 while( (c = getchar()) != EOF && len < max_size ){ 
 line[len++] = c; 
 if('\n' == c) 
  break; 
 } 


 line[len] = '\0'; 
 return len; 
} 

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

 //getline 
 int len; 
 while(0 != (len = my_getline(buff, max_size))){ 
 printf("Read line with len: %d\n", len); 
 printf("%s", buff); 
 } 

 free(buff); 
} 

二 c++读取一行字符串

cin.get()和cin.getline()
#include

using namespace std;

int main()
{

 cout << "----------getline忽略'\\n-----------------" << endl;
 char str0[30], str1[30];
 cin.getline(str0, 30);
 cin.getline(str1, 30);
 cout << "str0:" << str0 << endl;
 cout << "str1:" << str1 << endl;

 cout << "---------利用get()消除get()遗留下来的'\\n'-------" << endl;
 char str2[30], str3[30];
 cin.get(str2, 30).get(); // 注意这里!
 cin.get(str3, 30).get();
 cout << "str1: " << str2 << endl;
 cout << "str2: " << str3 << endl;

 cout << "--------没消除get()遗留下来的'\\n'就被下一个get()读取了,所以str5输出为空-----" << endl;
 char str4[30], str5[30];
 cin.get(str4, 30); // 注意这里!
 cin.get(str5, 30);
 cout << "str4: " << str4 << endl;
 cout << "str5: " << str5 << endl;
 return 0;

}

c读取一行字符串,以及c++读取一行字符串的实例

以上这篇c读取一行字符串,以及c++读取一行字符串的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持创新互联。


网站标题:c读取一行字符串,以及c++读取一行字符串的实例
分享URL:http://bjjierui.cn/article/pcpeps.html

其他资讯