很多情况下都需要用数组去解决问题,简单的一点题目会给出数组大小,然后你就可以通过for循环去读取每个元素;麻烦一点的题目不给你数组的大小,需要你自己去获取数组的长度和元素;
如,给定数组长度为9,每个元素分别为:8 3 6 9 9 9 0 0 1;
如,给定一个数组(长度未知)的每个元素分别为:8 3 6 9 9 9 0 0 1;
reference: https://blog.csdn.net/JIEJINQUANIL/article/details/50802902
其实,在线笔试的编程题是允许用户使用循环无限输入用户所需的数据,样例如下所示:
样例题目及程序
A + B
描述
给予两个整数 a 和 b ,计算它们的和 a + b
输入
输入包含多组测试数据,每一行包含两个整数 a 和 b
输出
在一行中输出 a + b 的值
#include <iostream>
using namespace std;
int main()
{
int a, b;
while(cin>> a >> b)
cout << a + b << endl;
return 0;
}
本文思路:
给定长度:
如,给定数组长度为9,每个元素分别为:8 3 6 9 9 9 0 0 1
1)直接使用 cin 手工输入
9
8 3 6 9 9 9 0 0 1
===== result info =====
9
8 3 6 9 9 9 0 0 1
--------------------------------
Process exited after 7.193 seconds with return value 0
请按任意键继续. . .
2)使用 ifstream 文件流读入数据
===== result info =====
9
8 3 6 9 9 9 0 0 1
--------------------------------
Process exited after 0.2704 seconds with return value 0
请按任意键继续. . .
代码如下,很简单就可以gao'din:
// 9
// 8 3 6 9 9 9 0 0 1
//
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
#define MAX_NUM 1000
int num;
int a[MAX_NUM];
void display(){
cout<<"===== result info ====="<<endl;
cout<<num<<endl;
for(int i=0; i<num; i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
void input_cin(){
cin >> num;
for(int i=0; i<num; i++)
{
cin>>a[i];
}
}
void input_ifstream(){
ifstream in_data;
in_data.open("./easy.txt");
in_data >> num;
for(int i=0; i<num; i++)
{
in_data >> a[i];
}
}
int main(){
// input_cin();
input_ifstream();
display();
return 0;
}
未给定长度:
如,给定一个数组(长度未知)的每个元素分别为:8 3 6 9 9 9 0 0 1
此时,就不像上述那么简单就可以搞定,整理了如下一些方法。如有问题,还望指出,谢谢~
1)遇回车结束:getchar()=='\n'
void input_cin(){
num = 0;
for(int i=0;;i++)
{
cin>>a[i];
num++;
if(getchar()=='\n') //遇回车结束
break;
}
display();
}
2)do{ cin>>input; } while(cin.get() != '\n');
void input_cin2(){
num = 0;
do{
cin >> a[num];
num++;
}while(cin.get() != '\n');
display();
}
3)文件读入:ifstream
@!%12dgsa
010111100
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
#define MAX_NUM 1010
vector<char> source;
vector<char> target;
int len = 0;
void get_data(){
ifstream in_data;
in_data.open("./data.txt");
char temp;
while(1){
temp = in_data.get();
if(temp == '\n'){
break;
}
source.push_back(temp);
len++;
}
for(int i=0; i<len; i++){
temp = in_data.get();
target.push_back(temp);
}
}
void display(){
cout<<"len = "<<len<<endl;
for(int i=0; i<len; i++){
cout<<source[i];
}
cout<<endl;
for(int i=0; i<len; i++){
cout<<target[i];
}
cout<<endl;
}
int main(){
get_data();
display();
return 0;
}
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
string s1, s2;
vector <char> c1;
getline(cin, s1);
getline(cin, s2);
for(int i=0; i<s1.length() ;i++){
cout<<s1[i]<<endl;
// c1.push_back(s1[i]);
}
for(int i=0; i<s2.length() ;i++){
cout<<s2[i]<<endl;
}
return 0;
}