我试图将我从文件中读入的字符串转换为int值,以便将其存储在整数变量中.这就是我的代码:
ifstream sin;
sin.open("movie_output.txt");
string line;
getline(sin,line);
myMovie.setYear(atoi(line));
Run Code Online (Sandbox Code Playgroud)
在这里,setYear是Movie类中的一个mutator(myMovie是Movie类的一个对象),如下所示:
void Movie::setYear(unsigned int year)
{
year_ = year;
}
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
Bil*_*eal 10
而不是使用std::getline(std::string&, std::istream&),为什么不在文件上使用流提取操作符?
ifstream sin;
sin.open("movie_output.txt");
unsigned int year = 0;
sin >> year;
myMovie.setYear(year);
Run Code Online (Sandbox Code Playgroud)
#include <boost/lexical_cast.hpp>
Run Code Online (Sandbox Code Playgroud)
使用lexical_cast:
int value = boost::lexical_cast<int>(line);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4790 次 |
| 最近记录: |