c讀取一行字符串,以及c++讀取一行字符串的實(shí)例
一 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í)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持我們。
上一篇:C/C++獲取鍵盤事件的方法
欄 目:C語言
下一篇:C語言實(shí)現(xiàn)linux網(wǎng)卡檢測精簡版
本文標(biāo)題:c讀取一行字符串,以及c++讀取一行字符串的實(shí)例
本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/751.html
您可能感興趣的文章
- 01-10深入解析最長公共子串
- 01-10C語言字符串操作總結(jié)大全(超詳細(xì))
- 01-10用c語言根據(jù)可變參數(shù)合成字符串的實(shí)現(xiàn)代碼
- 01-10如何用C語言去除字符串兩邊的空字符
- 01-10c語言字符數(shù)組與字符串的使用詳解
- 01-10用C實(shí)現(xiàn)添加和讀取配置文件函數(shù)
- 01-10使用C語言遞歸與非遞歸實(shí)現(xiàn)字符串反轉(zhuǎn)函數(shù)char *reverse(char *str
- 01-10c語言中用字符串?dāng)?shù)組顯示菜單的解決方法
- 01-10c++實(shí)現(xiàn)strcat字符串連接庫函數(shù)的方法詳解
- 01-10C++實(shí)現(xiàn)strcmp字符串比較的深入探討


閱讀排行
本欄相關(guān)
- 04-02c語言函數(shù)調(diào)用后清空內(nèi)存 c語言調(diào)用
- 04-02func函數(shù)+在C語言 func函數(shù)在c語言中
- 04-02c語言的正則匹配函數(shù) c語言正則表達(dá)
- 04-02c語言用函數(shù)寫分段 用c語言表示分段
- 04-02c語言中對數(shù)函數(shù)的表達(dá)式 c語言中對
- 04-02c語言編寫函數(shù)冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數(shù) round c語言
- 04-02c語言分段函數(shù)怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數(shù) c語言中怎
- 04-02c語言調(diào)用函數(shù)求fibo C語言調(diào)用函數(shù)求
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05織夢dedecms什么時(shí)候用欄目交叉功能?
- 01-10C#中split用法實(shí)例總結(jié)