如何从字符串中提取浮子?

发布于 2025-02-05 02:59:32 字数 401 浏览 1 评论 0原文

我试图从字符串中提取浮点数,然后将它们保存在数组中。

这是我发现的代码,即使我进行了必要的更改,但它行不通:

#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;
}

I am trying to extract float numbers from a string and after that they will be saved in an array.

Here's a code I found and even though I made the necessary changes it doesn't work:

#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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

还给你自由 2025-02-12 02:59:32

不要这样解析字符串。只需阅读所需语言环境中的值,例如大多数非英语欧洲地区,例如de_de.utf8ru_ru.utf8,或it_it.utf-8 ...您甚至可以为不同的流设置不同的位置,因此,下面我使用std :: cin和自定义的默认系统语言环境使用作为std :: Cout中的radix点

#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;
}

std :: locale(“”) 给您当前系统locale ,它可能是el_gr.utf -8在您的情况下。您还可以指定使用的特定语言环境,例如std :: locale(“ fr_fr.utf8”)。然后使用 std :: Locale :: locale :: global 在全球范围内设置获得的区域。每个特定的流都可以进一步 imbue d 在必要时到其他地方。您也可以使用 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上,您无法轻松地从控制台更改它,因此只需在代码中执行此操作即可。 And I'm printing the output directly but pushing it into an array is trivial

  • demo “> iDeone上的演示

请注意,这些在线平台没有非US的网站元素,因此我必须使用自定义语言环境。在Linux上,您可以使用locale -A检查可用的地区,


以防您真的想将浮点数作为字符串作为字符串(为什么?),然后只是正常阅读。无需进行这种复杂的解析。 std :: cin和任何种类的 istream /code>只会停在空格 expected

#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;
}

Sample output:

$ 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

Demo

Don't parse the string like that. Just read the values in your desired locale, for example most non-English European locales like de_DE.utf8, ru_RU.utf8, or it_IT.UTF-8... You can even set different locales for different streams, so for example below I'm using the default system locale for std::cin and a custom locale which uses : as the radix point in 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;
}

In C++ std::locale("") gives you the current system locale which is probably el_GR.UTF-8 in your case. You can also specify a specific locale to use such as std::locale("fr_FR.utf8"). Then use std::locale::global to set the obtained locale globally. Each specific stream can further be imbued to a different locale if necessary. You can also use setlocale for setting some locale preferences

Sample output:

$ 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

Notice the difference in the last output? That's because , is the thousand separator in the English locale

In the example above I'm setting the current locale via LC_ALL, but on Windows you can't change that easily from the console so just do that in your code. And I'm printing the output directly but pushing it into an array is trivial

Note that those online platforms don't have a non-US locale so I have to use the custom locale. On Linux you can check the available locales with locale -a


In case you really want to get the floating-point numbers as strings (why?) then just read normally. No need for such complex parsing. std::cin and any kinds of istream will just stop at blank spaces as expected

#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;
}

Sample output:

$ 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

Demo

星光不落少年眉 2025-02-12 02:59:32

如果您不太关心性能,则可以使用此简单算法:

#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”中的每个字符进行检查:

  • 如果数字或逗号 - &gt; 如果空间
  • - &gt;读取浮点结束(现在正在寻找新的),将缓冲区推到数组和清除缓冲区,以便您可以阅读新的浮点,

如果您想我解释一些有时可以提出要求:)

If you don't care about performance that much, you can use this simple algorithm :

#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;
}

this algorithm goes through every char inside 'a' and checks:

  • if digit or comma -> add it to buffer
  • if space -> reading float ended (now looking for a new one), pushing buffer to array and clearing buffer so you can read new float

if you want me to explain someting feel free to ask :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文