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

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

问题描述

我试图将我从一个文件中读取的字符串转换为int值,所以我可以将其存储在一个整数变量。这是我的代码看起来像:

I am trying to convert a string I read in from a file to an int value so I can store it in an integer variable. This is what my code looks like:

ifstream sin;  
sin.open("movie_output.txt");  
string line;  
getline(sin,line);  
myMovie.setYear(atoi(line));

在这里,setYear是Movie类中的一个mutator(myMovie是Movie类的一个对象)看起来像这样:

Over here, setYear is a mutator in the Movie class (myMovie is an object of Movie class) that looks like this:

void Movie::setYear(unsigned int year)  
{  
    year_ = year;  
}



当我运行代码时,我得到以下错误:

When I run the code, I get the following error:

error C2664: 'atoi' : cannot convert parameter 1 from 'std::string' to 'const char *'  
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called


推荐答案

myMovie.setYear(atoi(line.c_str()));

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

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