关于笔试中的数据输入问题

输入数据的行数和个数已知

这种情况下的数据输入就比较简单了

int n;
cin >> n;
vector<int> data(n, 0);
for(int i = 0; i < n; i ++ ) 
{
    cin >> data[i];
}

输入数据的行数和个数未知

每行的数据之间空格隔开,每行的数据个数不定,一直读到文件结束符为止

#include <iostream>
#include <sstream>
#include <vector>
#include <string>
using namespace std;

int main{
    stringstream ss;
    string s;
    vector<int> data;
    while(cin >> s)
    {
        ss << s;
        int num;
        while(ss >> num)
        {
            data.push_back(num);
        }
    }
    return 0;
}

当输入的数据行数已知,每行输入的数据个数未知的情况下:

#include<iostream>
#include<vector>
#include<cstring>
#include <sstream>
 
using namespace std;
 
int main(void)
{
	vector<int> A;  //输入第一行的数据到数组A
	vector<int> B;  //输入第二行的数据到数组B
	
	int num;
	string str;
	int cnt = 0; //控制输入数据的行数,行数为已知的情况
	while (getline(cin, str))
	{
		//if (str.size() == 0)break;  //控制输入数据的行数,行数为未知的情况
		istringstream ist(str);
		while (ist >> num)
		{
			if (cnt == 0)
			{
				A.push_back(num);
			}
			else
			{
				B.push_back(num);
			}
		}
		cnt++;
		if (cnt == 2)
			break;
	}
    return 0;
}

程序中的 if(str.size() == 0) break;   也可以在数据输入的行数未知的情况下,控制数据输入的行数

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值