将字符串转换为long [英] Converting string to long

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

问题描述

我想将字符串转换为long。这听起来很容易,但我仍然得到相同的错误。我试过:

I'm trying to convert a string to long. It sounds easy, but I still get the same error. I tried:

include <iostream>
include <string>    

using namespace std;

int main()
{
  string myString = "";
  cin >> myString;
  long myLong = atol(myString);
}

但总是出现错误:

.../main.cpp:12: error: cannot convert 'std::string {aka std::basic_string<char>}' to 'const char*' for argument '1' to 'long int atol(const char*)'



<
引用说明如下:

occured. The reference says following:

long int atol ( const char * str );

任何帮助?

推荐答案

尝试

long myLong = std::stol( myString );

此函数有三个参数:

long stol(const string& str, size_t *idx = 0, int base = 10);

您可以使用第二个参数来确定字符串中解析数字的位置。例如

You can use the second parameter that to determine the position in the string where parsing of the number was stoped. For example

std::string s( "123a" );

size_t n;

std::stol( s, &n );

std::cout << n << std::endl;

输出为

3

函式可能会抛出异常。

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

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