在C ++中将字符串转换为int [英] Convert string to int in C++

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

问题描述

我有一个字符串xxxxxxxxxxxxxxxxxxx

我正在将字符串读取为较小字符串的结构,并使用substr对其进行解析. 我需要将其中一种字符串类型转换为整数.

I am reading the string into a structure of smaller strings, and using substr to parse it. I need to convert one of those string types to integer.

atoi对我不起作用.有任何想法吗?它说cannot convert std::string to const char*

atoi is not working for me,. any ideas? it says cannot convert std::string to const char*

谢谢

#include<iostream>

#include<string>

using namespace std;

void main();

{
    string s="453"

        int y=atoi(S);
}

推荐答案

要求const char *传递.

将其更改为:

int y = atoi(s.c_str());

或使用 std::stoi() ,您可以通过直接:

or use std::stoi() which you can pass a string directly:

int y = stoi(s);


您的程序还有其他几个错误.可行的代码可能类似于:


You program has several other errors. Workable code could be something like:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string s = "453";
    int y = atoi(s.c_str());
    // int y = stoi(s); // another method
}

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

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