c讀取一行字符串,以及c++讀取一行字符串的實(shí)例
更新時(shí)間:2018年07月12日 10:47:06 作者:HxShine
今天小編就為大家分享一篇c讀取一行字符串,以及c++讀取一行字符串的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
一 c讀取一行字符串
1 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);
}
利用getchar()讀取一個(gè)個(gè)字符來讀取一行
#include <stdio.h>
#include <stdlib.h>
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<iostream>
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'就被下一個(gè)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++讀取一行字符串的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
總結(jié)C/C++面試中可能會(huì)碰到的字符串指針題
C/C++是最能體現(xiàn)程序員能力的語言之一,其功能強(qiáng)大,在IT行業(yè)的各個(gè)方面都有大量的應(yīng)用。下面這篇文章主要介紹了總結(jié)了在C/C++面試中可能會(huì)碰到的字符串指針題,需要的朋友可以參考借鑒,下面來一起看看吧。2017-01-01
OpenCV+Qt實(shí)現(xiàn)圖像處理操作工具的示例代碼
這篇文章主要介紹了利用OpenCV+Qt實(shí)現(xiàn)圖像處理操作工具,可以實(shí)現(xiàn)雪花屏、高斯模糊、中值濾波、毛玻璃等操作,感興趣的可以了解一下2022-08-08
Matlab實(shí)現(xiàn)簡(jiǎn)單擴(kuò)頻語音水印算法詳解
本文主要介紹了通過MATLAB設(shè)計(jì)并實(shí)現(xiàn)一種基于音頻的擴(kuò)頻水印算法,從而了解參數(shù)對(duì)擴(kuò)頻水印算法性能的影響。代碼具有一定的價(jià)值,感興趣的小伙伴可以關(guān)注一下2021-11-11
深入了解C語言的動(dòng)態(tài)內(nèi)存管理
所謂動(dòng)態(tài)和靜態(tài)就是指內(nèi)存的分配方式。動(dòng)態(tài)內(nèi)存是指在堆上分配的內(nèi)存,而靜態(tài)內(nèi)存是指在棧上分配的內(nèi)存,本文將用5600字帶你深入了解動(dòng)態(tài)內(nèi)存管理,感興趣的可以學(xué)習(xí)一下2022-07-07

