从文件中读取编号,递增并写回

Read number from file, increment and write back

本文关键字:写回 编号 文件 读取      更新时间:2023-10-16

我想从文件中读取一个long号,然后递增它并将其写回文件。
我正在努力从string转换到long再转换回来。

我试过了:

double id = atof("12345678901"); //using atof because numbers are too big for atio()
id++;
ostringstream strs;
strs << static_cast<long>((static_cast<double>(threadId)));
string output = strcpy_s(config->m_threadId, 20, strs.str().c_str());

但这会将输入转换为负数或错误数字。

atoi适用于普通整数。还有atolatoll_atoi64在窗口中):

//long long id = atoll( "12345678901" );
long long id = _atoi64("12345678901"); // for Visual Studio 2010
id++;
// write back to file here

正如一位评论者所建议的那样,使用 strtoll 而不是 ato* 函数:

char * data = "12345678901";
long long id = strtoull( data, NULL, 10 );
id++;

由于您在此处使用C++,因此您应该直接从流中提取它:

long long id;
{  
   std::ifstream in( "numberfile.txt" );
   in >> id;
}
id++;
{
   std::ofstream out( "numberfile.txt" );
   out << id;
}

要从 C 字符串( char 数组),请使用以下命令:

long id = atol("12345678901");

现在,您可以递增该数字。然后,要从long转到C++ std::string,请使用以下命令:

std::ostringstream oss;
oss << id;
std::string idAsStr = oss.str();

现在,您可以将字符串写回文件。

您是否可以访问Boost.Lexical_Cast?您可以简单地进行这样的转换:

double id = boost::lexical_cast<double>("some string");
++id
std::string id_string = boost::lexical_cast<std::string>(id);

并使用您当前拥有的任何文件传输。