文章目录
前言
C++中的输入输出函数有很多,我们本章只针对大部分算法题的输入输出。
一、输入输出方法
1、cin
cin
是C++
中, 标准的输入流对象
注意:cin
以空格、tab、换行符作为分隔符
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num;
cout << num << endl;
return 0;
}
2、getline()
cin
在读取字符串间有空格的时候会被打断,这时候就需要getline()
函数
注意:getline()
遇到换行符结束
#include <iostream>
#include "string"
using namespace std;
int main() {
string str;
getline(cin, str);
cout << str << endl;
return 0;
}
3、getchar()
从缓存区中读出一个字符
#include <iostream>
using namespace std;
int main() {
char ch;
ch = getchar();
cout << ch << endl;
return 0;
}
二、算法案例
1、一维数组
1.1 输入固定长度
首先输入
待输入
元素个数,然后输入元素(以空格隔开)
注意这里的元素也可以是其他数据类型,比如字符串abc
,只需要修改vector
为对应的数据类型
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> vec(n);
for (int i =