如何使用 cin 处理以下输入
How do I process following kind of input using cin?
输入如下:
2
3 2 1 4
10.3 12.1 2.9 1.9
2 1 3
9.8 2.3 1.2
所以 2 是测试用例的数量。然后有一个空行。然后是测试用例。单个测试由两行分别是整数值和浮点值组成。整数数等于浮点值数。然后再次出现一个空行,然后是第二个测试。
我面临两个问题:首先,如果我知道将有多少个数字,我可以用于循环,第二个在测试用例之后和测试用例之间有空行。我不知道如何使用 cin 阅读它们或忽略它们。我将把这些值存储在向量中。谢谢
您可以使用
getline
函数读取行,例如:
string line;
std::getline(std::cin, line);
然后,您需要解析该行。有两种情况(在读取测试用例数量后)。要么你碰到一个空行,要么有n
整数。您可以逐个读取整数并将它们添加到向量中。如果在缓冲区完成后得到 0 个整数,则它是一个空行:
unsigned int n;
std::ostringstream sin(line);
while (sin >> number)
{
// add number to your vector
++n;
}
if (n == 0)
// go back and try getline again
现在你已经有了n
,阅读下一行带有浮点数应该很容易。只需使用循环,因为您知道浮点数与每个测试用例的整数数相同。
我认为以下程序可以满足您的需求。
#include <iostream>
#include <iterator>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
int main() {
// Identify the number of tests
std::string ntests_str;
std::getline(std::cin, ntests_str);
int ntests = boost::lexical_cast<int>(ntests_str);
// Iterate over all tests
for (int i = 0; i < ntests; i++) {
// Read the integer numbers
std::string integers;
while (integers.empty())
std::getline(std::cin, integers);
// Split the integers into a vector of strings
std::vector<std::string> intstr_vec;
boost::split(intstr_vec, integers, boost::is_any_of(" "));
// Convert to integers
std::vector<int> int_vec;
int_vec.resize(intstr_vec.size());
std::transform(intstr_vec.begin(), intstr_vec.end(), int_vec.begin(),
[&](const std::string& s) {
return boost::lexical_cast<int>(s);
}
);
// Read the floating point numbers
std::string fnumbers;
std::getline(std::cin, fnumbers);
// Split the floating-point numbers into a vector of strings
std::vector<std::string> fstr_vec;
boost::split(fstr_vec, fnumbers, boost::is_any_of(" "));
// Convert the floating point numbers
std::vector<float> float_vec;
float_vec.resize(fstr_vec.size());
std::transform(fstr_vec.begin(), fstr_vec.end(), float_vec.begin(),
[&](const std::string& s) {
return boost::lexical_cast<float>(s);
}
);
// Print the test case
std::cout << "== Test case " << i << std::endl;
std::cout << "Integers: ";
std::copy(int_vec.begin(), int_vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
std::cout << "Floats: ";
std::copy(float_vec.begin(), float_vec.end(), std::ostream_iterator<float>(std::cout, " "));
std::cout << std::endl;
std::cout << std::endl;
}
return 0;
}
例:
./prog1
1
3 2 1 4
10.3 12.1 2.9 1.9
== Test case 0
Integers: 3 2 1 4
Floats: 10.3 12.1 2.9 1.9
相关文章:
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 如何处理包含空格的 cin 的用户输入?
- C++ 如何处理所有可能的玩家移动输入?
- 该程序允许用户处理循环,只要用户输入奇数
- 全新C++.处理用户输入
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- 重定向输入和输出时如何处理主文件I/O?
- 有没有办法在使用 GLFW 按下按键后只处理一个输入事件?
- 输入处理程序函数中的分段错误
- 是否有任何内置的哈希图函数来处理 c++ 中的值输入?
- 为什么我的代码无法处理大型数组输入(>10000)?
- 处理输入流运算符>>中的无效输入
- 异常处理:如果用户输入不是三个特定字符之一
- 我正在努力处理多维数组输入和输出,我管理输入,但是打印无法按计划工作
- SDL C++鼠标输入处理切换效果
- C++ GLFW3 输入处理
- 组件实体系统-输入处理
- 带有WM_CHAR输入处理文本框中的GobbledyGook
- GLFW 输入处理未按预期工作
- c++简单的输入处理(由空格分隔的两个字符数组)