在C++中从字符串中删除非整数

jke*_*eys 2 c++ casting variable-assignment

在我的一本书中有一篇关于人们将逗号输入整数并弄乱你的程序的评论,但它没有详细说明.这让我思考,所以我尝试编写一个小算法来获取std :: string并删除所有非整数字符.此代码编译但跳过输出.为什么没有任何内容被分配给newstring?if(isdigit(fstring [i]))是否评估为指向持有数字的地址为真?

//little algorithm to take the non-integers out of a string
//no idea on efficiency

#include <iostream>
#include <string>

int main()
{
    std::cout << "Enter a number with non-integer characters: ";

    std::string fstring; 
    getline(std::cin, fstring);

    std::string newstring;

    int i = 0, x = 0;

    while (i != fstring.length())
    {
        if (isdigit(fstring[i]))
        {
            newstring[x] = fstring[i];
            i++;
            x++;
        }
        else
        {
           i++;
        }
    }

    std::cout << std::endl;
    std::cout << newstring;
    system("PAUSE");
}
Run Code Online (Sandbox Code Playgroud)

次要问题,可能属于其他地方:如何将字符串转换为int(或浮点数)?

the*_*met 6

newstring的长度为0,所以newstring [x]其中x = 0实际上是非法的.你应该使用:newstring.append(1,fstring [i])追加到字符串

对于次要问题,请查找atoi(),atof(),strtol(0,strtof()函数.

  • 当你保留时,你在内部说"确保我能保持这么多",当你*调整*时,你实际上说"保持这么多" (3认同)
  • 因为保留,就像向量上的保留一样,不会改变字符串的大小,它会改变它的容量.输出时,字符串的长度仍为零,即使它已分配足够的空间来容纳更多数据. (2认同)

Log*_*ldo 5

字符串类似于数组,但字符串的默认构造函数会创建一个空字符串.为什么要分配比它需要更多的内存?即使它确实如此,也没有说多少,或者它是否足够大,可以过滤fstring的副本.我印象深刻它没有崩溃.

一个简单的修改就是改变:

std::string newstring;
Run Code Online (Sandbox Code Playgroud)

至:

 std::string newstring(fstring.length(), '\0')
Run Code Online (Sandbox Code Playgroud)

并在循环后添加:

 newstring.resize(x);
Run Code Online (Sandbox Code Playgroud)

这将确保newstring在过滤期间至少有足够的空间(可能更多),并在完成过滤后将其修剪到合适的尺寸.您可能也对该std::remove_copy_if功能感兴趣<algorithm>.

例如

struct isnotdigit { bool operator()(char c) { return !isdigit(c); } };

std::string newstring(fstring.length(), '\0');
std::string::iterator i = std::remove_copy_if(fstring.begin(), 
  fstring.end(), newstring.begin(), isnotdigit());
newstring.erase(i, newstring.end());
Run Code Online (Sandbox Code Playgroud)

作为一个字符串转换为整数/浮点除atoi,strtol,atof,strtof,等功能已经提到的,您还可以使用iostream库的:

 #include <sstream>
 std::string integer("23");
 std::istringstream iss(integer);
 int result;
 iss >> result;

 std::string floatingpoint("3.14");
 std::istringstream iss2(floatingpoint);
 double result2;
 iss2 >> result2;
Run Code Online (Sandbox Code Playgroud)

此外,如果您熟悉printf系列函数,您可能会感兴趣scanf,sscanf

 const char *s = "23";
 int result;
 sscanf(s, "%d", &result);
Run Code Online (Sandbox Code Playgroud)