2016-05-04 5 views
-2

を変換:は、文字列のラインを取得し、私は次のことを達成するために必要なフロートリストに

"4 5 1.3 0 3.1" 

これは私がユーザーから読み込みます入力文字列で、読んだ後、私はにこの文字列をオンにする必要があります例えば[0]番目の文字のサイズに応じてフロートリストは、リストには、私は私がgetlineが、didntの仕事を使用してみました、それを達成することができますどのように

array[4] = [5.0,1,3,0.0,3.1] 

になります。前もって感謝します。

+0

stringstreamとnewを試しましたか? –

+0

ええ、0番目のインデックスは、stringstreamのループが必要だと思っているので、あまり適さないのです。 –

+2

あなたのしたことを教えてください。 –

答えて

0
string line = "4 5 1.3 0 3.1"; // input string 
istringstream stream(line); // parser 
unsigned count; // how many values 
double* values; 
if (stream >> count) { 
    values = new double[count]; 
    for (unsigned ii = 0; ii < count; ++ii) { 
     stream >> values[ii]; // read one 
     if (!stream) { 
      throw std::runtime_error("not enough numbers"); 
     } 
    } 
} else { 
    throw std::runtime_error("no count at start of line"); 
} 

// do something with values... 

delete[] values; 
+0

ありがとうございます。ベクトルなしでこれを行う方法はありますか? –

+0

@BallsyCoder:確かに、ベクトルの代わりに 'new []'と 'delete []'を使うように変更しました。これはあまり良い習慣ではありません(少なくとも明示的な削除を避けるためにスマートポインタを使うべきです)が、運動/教授のためにはうまくいくでしょう。 –

0

最初にカウントを符号なし整数に読み込み、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、それを包むことによってクリーンアップされることを保証します。

関連する問題