輸入如下:如何使用cin處理以下類型的輸入?
2
3 2 1 4
10.3 12.1 2.9 1.9
2 1 3
9.8 2.3 1.2
SO 2是測試用例的數目。然後是空行。然後是一個測試用例。單個測試由兩行分別爲整數和浮點值組成。整數的數量等於浮點值的數量。然後再次空白行和第二次測試。
我面臨兩個問題:首先,如果我知道有多少數字可以用於循環,第二個數據是測試用例之後和測試用例之間是空行。我不知道如何使用cin讀取它們或忽略它們。我會將這些值存儲在向量中。由於
輸入如下:如何使用cin處理以下類型的輸入?
2
3 2 1 4
10.3 12.1 2.9 1.9
2 1 3
9.8 2.3 1.2
SO 2是測試用例的數目。然後是空行。然後是一個測試用例。單個測試由兩行分別爲整數和浮點值組成。整數的數量等於浮點值的數量。然後再次空白行和第二次測試。
我面臨兩個問題:首先,如果我知道有多少數字可以用於循環,第二個數據是測試用例之後和測試用例之間是空行。我不知道如何使用cin讀取它們或忽略它們。我會將這些值存儲在向量中。由於
可以使用getline
函數讀取線路,如:
string line;
std::getline(std::cin, line);
然後,你需要解析線。有兩種情況(讀取測試用例的數量後)。要麼你打空白線,要麼有整數。您可以逐個讀取整數並將它們添加到您的矢量中。如果你得到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
你知道getline'和'ostringstream'的'? – Shahbaz
我知道getline,但不是ostringstream。我知道我可以使用getline(cin,s)來讀取字符串s中的新行。我想用cin和'\ n'來做。 – rishiag
只有'cin',你不能(我想)知道你什麼時候通過了一條線。在這種情況下,最好的解決方案是讀取一行,將其傳遞給ostringstream sin(the_line);'並讀取while(sin >> num){...} – Shahbaz