基礎
1、getchar()
頭文件#include<cstdio>
中
從標準輸入讀下一個字符。原返回int(如輸入a,函數返回97)。
2、getline()
讀入一行字符串,以換行結束。
應用:實現輸入
1、讀一行整數,以換行結束。便輸出。
輸入: 10 20 30 80 70
輸出: 10 20 30 80 70
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main(){
int num;
vector<int> v;
while(cin>>num){
v.push_back(num);
char ch= gerchar();//讀取下一個字符,爲換行符,則break
if(ch=='\n')
break;
}
//輸出略。
return 0;
}
2、讀一行句子以換行結束
string words;
getline(cin, words);//讀入一行字符串,遇到換行結束
cout<< words<<endl;
3、讀多行字符串
假如讀一組字符串。注意用while(getline(cin, str))要寫上if(str.size()==0) break;
才能結束循環。
輸入:
li xiao ming
gao yang
chen chen
liu wen
#include <iostream>
#include <cstdio>
#include <vector>
using namespace std;
int main(){
string str;
vector<string> str_list;
while(getline(cin, str){
if(str.size()==0) break;//記得要這句,才能結束輸入
str_list.push_back(str);
}
cout<< str_list.size()<<endl;
for(auto s: str_list){
cout<< s << endl;
}
return 0;
}
輸出:
4
li xiao ming
gao yang
chen chen
liu wen