项目场景:
网易秋招笔试第一题,自己本地调试的时候卡在了数据输入,实尬。。。
问题描述:
【ACM模式】求数组中两个数之和小于指定数的两数组合数。
输入两行数据,第一行是数组,第二行是目标数M,输出组合数目。
示例:
输入:
-1 -1 7
9
输出:
3
解析: [-1,-1],[-1,7],[-1,7] 的和都小于9
int main(){
vector<int> input;
int a;
while (cin >> a) {
cout << a << endl;
input.push_back(a);
}
int M = input[input.size() - 1];
...
}
输入两行数据,然后呢?然后怎么结束呢?回车不能结束读取吗?【懵逼了】
解决方案:
控制台输入时以 Ctrl+Z(Windows) or Ctrl + D(Linux) 结束输入
在这里也记录一下后来学到的控制台多行数据输入方法吧 原出处
1. 多行整数输入:通过getline()和istringstream实现
#include <iostream>
#include <string>
# include <vector>
#include <sstream>
using namespace std;
int main()
{
vector<vector<int> > nums; //二维数组保存多行数
string str; //接收带空格的字符串
int num; //读入的数
// 输入多行整数
while (getline(cin, str))
{
istringstream iss(str);//从str中读入字符
vector<int> v; //一维数组存一行数
while (iss >> num)
{
v.push_back(num);
}
nums.push_back(v);
}
// 输出验证
for (int i = 0; i < nums.size(); ++i)
{
for (int j = 0; j < nums[i].size(); ++j)
{
cout << nums[i][j] << " ";
}
cout << endl;
}
}
测试效果:
- 多行字符串输入
#include <iostream>
#include <string>
# include <vector>
#include <sstream>
using namespace std;
int main()
{
vector<vector<string> >strs;
string strline;
string str;
// 输入:逐行读取,解析
while (getline(cin, strline)) // 读入一行
{
if (strline.size() == 0) break;
// 解析一行
istringstream iss(strline);
vector<string> v;
while (iss >> str)
{
v.push_back(str);
}
strs.push_back(v);
v.clear();
}
// 输出验证
for (int i = 0; i < strs.size(); ++i)
{
for (int j = 0; j < strs[i].size(); ++j)
{
cout << strs[i][j] << " ";
}
cout << endl;
}
}
测试效果
其他注意:
Ctrl+Z(Windows) or Ctrl + D(Linux)结束输入表示的是结束当前程序的输入,不会在当前程序中再开启一次输入
#include <iostream>
#include <string>
# include <vector>
#include <sstream>
using namespace std;
int main()
{
vector<vector<string> >strs;
string strline;
string str;
// 输入:逐行读取,解析
while (getline(cin, strline)) // 读入一行
{
if (strline.size() == 0) break;
// 解析一行
istringstream iss(strline);
vector<string> v;
while (iss >> str)
{
v.push_back(str);
}
strs.push_back(v);
v.clear();
}
// 再次输入
string newstr;
getline(cin,newstr);
// 输出验证
for (int i = 0; i < strs.size(); ++i)
{
for (int j = 0; j < strs[i].size(); ++j)
{
cout << strs[i][j] << " ";
}
cout << endl;
}
cout << newstr << endl;
}
测试效果:只能实现一次输入,Ctrl+Z后没有提供下一次输入的入口
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<int> input;
int a;
while (cin >> a) {
input.push_back(a);
}
int M = -1;
cin >> M;
// 输出验证
for (auto v : input) {
cout << v << " ";
}
cout << endl << M << endl;
}
测试效果: