c ++将字符串转换为int [英] c++ converting string to int

查看:130
本文介绍了c ++将字符串转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

//sLine is the string
for(int l = 0; l < sLine.length(); l++)
{
    string sNumber;
    if(sLine[l] == '-')
    {   
        sNumber.push_back(sLine[l]);
        sNumber.push_back(sLine[l + 1]);
        l++;
    }
    else if(sLine[l] != '\t')
    {
        sNumber.push_back(sLine[l]);
    }
    const char* testing = sNumber.c_str();
    int num = atoi(testing);
    cout << num;
}

我有这个for循环,检查字符串的每个字符并转换每个字符串此字符串中的数字为int。但由于某种原因,atoi功能正在做两次,所以当我开始它时,由于某种原因它会显示两次......为什么会这样?

I have this for-loop which checks each character of the string and converts every number in this string to be a int. But for some reason, the atoi function is doing it twice so when I cout it, it displays it twice for some reason... Why is that?

示例:
输入
3 3 -3 9 5

-8 -2 9 7 1

-7 8 4 4 -8

- 9 -9 -1 -4 -8

example: INPUT 3 3 -3 9 5
-8 -2 9 7 1
-7 8 4 4 -8
-9 -9 -1 -4 -8

OUTPUT
3030-309050
-80-20907010

-70804040- 80

-90-90-10-40-80

OUTPUT 3030-309050 -80-20907010
-70804040-80
-90-90-10-40-80

推荐答案

它显示所有未识别的零字符,因为 atoi 在给定非数字字符串(如空格!)时返回 0

It's displaying a zero for all nonrecognized characters, because atoi returns 0 when given a non-numeric string (like a space!)

然而,你想做的事情,简单起见:

However, what you want to do, is shockingly simple:

std::stringstream ss(sLine);
int num;
while(ss >> num) {
    cout << num;
}

这篇关于c ++将字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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