文字列をどのように変換しますか? string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";
を浮動小数点配列に変換します。float Numbers[6] = {0.3, 5.7, 9.8, 6.2, 0.54, 6.3};
?文字列を浮動小数点数の配列に変換するにはどうすればよいですか?
答えて
私はstd::
からデータ構造とアルゴリズムを使用します。
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cassert>
#include <sstream>
int main() {
std::string Numbers = "0.3 5.7 9.8 6.2 0.54 6.3";
// If possible, always prefer std::vector to naked array
std::vector<float> v;
// Build an istream that holds the input string
std::istringstream iss(Numbers);
// Iterate over the istream, using >> to grab floats
// and push_back to store them in the vector
std::copy(std::istream_iterator<float>(iss),
std::istream_iterator<float>(),
std::back_inserter(v));
// Put the result on standard out
std::copy(v.begin(), v.end(),
std::ostream_iterator<float>(std::cout, ", "));
std::cout << "\n";
}
あなたは 'using namespace std'を使わなかった特別な理由はありますか? – Sean
はい。 'using namespace std'はバグを導入することができます。問題のOK説明はここにあります:http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-a-bad-practice-in-c –
@Sean:答えを読む[ここで](http://stackoverflow.com/questions/1265039/using-std-namespace)最もupvotes(私は決してそれを使用することをお勧めします)。 –
私はいくつかの検索を行なったし、はstrtokために指摘しているように見えたが、他の検索は、あなたがより多くのカスタム関数を必要とするだろうと言っているように見えました。他の人がここで答えなかったら、あなたは私がしたよりも良い答えをGoogleで見つけることができます。 – TecBrat
そうですね、それは私の考えでした。私は 'strtok()'を使って個々の文字列に分割しようとしていましたが、 'atof()'を使って文字列を浮動小数点に変換しました(私は初心者のプログラマです)文字列をアップします。 – Sean