[英]How to extract floats from a string?
我正在嘗試從字符串中提取浮點數,然后將它們保存在數組中。
這是我找到的代碼,即使我進行了必要的更改,它也不起作用:
#include <iostream>
#include <string>
using namespace std;
string a="2,134 43,54 22,334";
string b[30];
int found,i=0;
while(a!="\0"){
found=a,find("\t");
for(int f=0;f<found;f++){
b[i]+=a[f];
}
a.erase(0,found+1);
i++;
}
for(int d=0;d<i;d++){
cout<<b[d]<<endl;
}
return 0;
}
不要像那樣解析字符串。 只需讀取所需語言環境中的值,例如大多數非英語歐洲語言環境,如de_DE.utf8
、 ru_RU.utf8
或it_IT.UTF-8
...您甚至可以為不同的流設置不同的語言環境,例如下面我'm 使用std::cin
的默認系統語言環境和使用:
作為std::cout
中的小數點的自定義語言環境
#include <iostream>
#include <sstream>
#include <locale>
#include <clocale>
#include <stdlib.h>
template <class charT, charT sep>
class punct_facet: public std::numpunct<charT> {
protected:
charT do_decimal_point() const { return sep; }
};
int main(int argc, char** argv) {
// Use default locale for most std streams
std::locale::global(std::locale(""));
// Use C locale with custom radix point for stdout
std::cout.imbue(std::locale(std::locale("C"), new punct_facet<char, ':'>));
std::stringstream str(argv[1]);
double d;
while (str >> d)
{
std::cout << d << '\n';
}
return 0;
}
在 C++ 中std::locale("")
為您提供當前系統語言環境,在您的情況下可能是el_GR.UTF-8
。 您還可以指定要使用的特定語言環境,例如std::locale("fr_FR.utf8")
。 然后使用std::locale::global
設置獲取的語言環境。 如果需要,每個特定的流可以進一步被imbue
到不同的語言環境。 您還可以使用setlocale
設置一些區域設置首選項
樣本輸出:
$ g++ read_locale.cpp -o read_locale
$ LC_ALL=el_GR.UTF-8 ./read_locale "2,134 43,54 22,334"
2:134
43:54
22:334
$ LC_ALL=en_US.utf8 ./read_locale "2.134 43.54 22,334"
2:134
43:54
22334
注意到最后一個輸出的不同了嗎? 那是因為,
是英語語言環境中的千位分隔符
在上面的示例中,我通過LC_ALL
設置當前語言環境,但在 Windows 上,您無法從控制台輕松更改,因此只需在代碼中執行此操作即可。 我直接打印輸出但是將它推入數組是微不足道的
請注意,這些在線平台沒有非美國語言環境,因此我必須使用自定義語言環境。 在 Linux 上,您可以使用locale -a
檢查可用的語言環境
如果您真的想將浮點數作為字符串(為什么?)然后正常讀取。 不需要如此復雜的解析。 std::cin
和任何類型的istream
都會按預期停在空白處
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char** argv) {
std::stringstream str(argv[1]);
std::string s;
while (str >> s)
{
std::cout << s << '\n';
}
return 0;
}
樣本輸出:
$ g++ read_numbers_as_string.cpp -o read_numbers_as_string
$ ./read_numbers_as_string "2,134 43,54 22,334"
2,134
43,54
22,334
如果你不太關心性能,你可以使用這個簡單的算法:
#include <iostream>
#include <vector>
int main()
{
std::string a = "2,134 43,54 22,334";
std::vector<std::string> floats; // I used vector instead of array - easier and safer
std::string buffer;
for (auto& itr : a)
{
if (itr == ' ') // space -- float ended
{
floats.push_back(buffer);
buffer.erase();
}
else
{
buffer += itr;
}
}
if (!buffer.empty()) // if something left in the buffer -> push it
floats.push_back(buffer);
// printing 'floats' array
for (auto& itr : floats)
std::cout << itr << '\n';
return 0;
}
該算法遍歷“a”中的每個字符並檢查:
如果你想讓我解釋一下,請隨時問:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.