最初にカウントを符号なし整数に読み込み、0からカウントまでループし、倍精度を読み込みます。配列を読み込むには、最初に正しいサイズで動的に配列を割り当てます。より良い、あなたのための割り当てを処理するstd::vector
を使用してください。
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
int main() {
std::string line;
std::getline(std::cin, line);
std::istringstream ss(line);
size_t num_values = 0;
if (! (ss >> num_values)) {
std::cerr << "Could not read the integer number of values!\n";
return 1;
}
auto values = std::make_unique<double[]>(num_values);
double tmp;
for (size_t idx = 0; idx < num_values; ++idx) {
if (! (ss >> values[idx])) {
std::cerr << "Could not convert the " << idx << "th value!\n";
return 1;
}
}
// Validate solution: print the contents of the vector
for (size_t idx = 0; idx < num_values; ++idx) {
std::cout << values[idx] << " ";
}
std::cout << "\n";
}
[live example]
この解決策は、動的に割り当てられた配列を使用し、そのメモリが正しくstd::make_unique
への呼び出しを介して作成std::unique_ptr
、それを包むことによってクリーンアップされることを保証します。
stringstreamとnewを試しましたか? –
ええ、0番目のインデックスは、stringstreamのループが必要だと思っているので、あまり適さないのです。 –
あなたのしたことを教えてください。 –