[英]converting string to int in C++
我試圖將我從文件中讀入的字符串轉換為int值,以便將其存儲在整數變量中。 這就是我的代碼:
ifstream sin;
sin.open("movie_output.txt");
string line;
getline(sin,line);
myMovie.setYear(atoi(line));
在這里,setYear是Movie類中的一個mutator(myMovie是Movie類的一個對象),如下所示:
void Movie::setYear(unsigned int year)
{
year_ = year;
}
當我運行代碼時,我收到以下錯誤:
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
而不是使用std::getline(std::string&, std::istream&)
,為什么不在文件上使用流提取運算符呢?
ifstream sin;
sin.open("movie_output.txt");
unsigned int year = 0;
sin >> year;
myMovie.setYear(year);
myMovie.setYear(atoi(line.c_str()));
#include <boost/lexical_cast.hpp>
使用lexical_cast:
int value = boost::lexical_cast<int>(line);
你可以做atoi(line.c_str())
另一種使用C ++流的方法是:
stringstream ss(line);
unsigned int year;
ss >> year;
快速解決方法是使用line.c_str()為atoi()提供const char *。
更好的解決方案(如果可用)可能是使用boost :: lexical_cast(line)。 這是C ++主題的一個更簡潔的版本,可以將內容輸入和輸出std :: stringstream,它具有您可能需要的所有類型轉換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.