在C ++中从字符串中删除非整数 [英] Removing non-integers from a string in C++

查看:229
本文介绍了在C ++中从字符串中删除非整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一本书中有一个传球评论,人们输入逗号成整数和混乱你的程序,但它没有详细说明。这让我想,所以我试着写一个小的算法,采取一个std :: string并删除所有非整数字符。此代码编译但跳过输出。为什么没有任何东西分配给newstring? if(isdigit(fstring [i]))是否指向保存一个数字的地址为真?

There was a passing comment in a book of mine about people inputting commas into integers and messing up your program, but it didn't elaborate. That got me thinking, so I tried writing a little algorithm to take an std::string and remove all non-integer characters. This code compiles but skips over output. Why isn't anything being assigned to newstring? Does if(isdigit(fstring[i])) evaluate to true of the address it's pointing to hold a digit?

//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");
}

次要问题,也许属于别处:如何将字符串转换为int(或浮点数)?

Secondary question, that perhaps belongs elsewhere: how do you convert a string to an int (or a floating point number)?

推荐答案

newstring的长度为0,所以newstring [x]实际上是非法的。您应该使用以下命令附加到字符串:newstring.append(1,fstring [i])

newstring is of length 0, so newstring[x] where x=0 is actually illegal. You should append to the string using: newstring.append(1, fstring[i])

对于第二个问题,寻找atoi(),atof (0,strtof()函数。

For the secondary question, look for atoi(), atof(), strtol(0, strtof() functions.

这篇关于在C ++中从字符串中删除非整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆