从文件中读取编号,递增并写回
Read number from file, increment and write back
我想从文件中读取一个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
适用于普通整数。还有atol
和atoll
(_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);
并使用您当前拥有的任何文件传输。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 将较大的整数写为二进制并读回它们会产生不好的结果
- 从文件中读取.txt字符串无法正确打印,但是当写回文件时,它很好
- 使用 select() 的请求/回复服务器。无法写回客户端
- 使用sokcet编程回写期间的数据丢失
- 我在不使用string.h的情况下写了一个C++回文.在没有 Do-While 循环的情况下,它可以正常工作.但是当我尝
- std::矢量写/回读会产生乱码
- IF流CSV从带逗号的文件写回
- 从文件中读取编号,递增并写回
- 写回全局变量
- C++ 读取 UTF-8 文件正常,转换为 UTF-16 正常,写回文件不正常
- OpenCL写回缓冲区
- 如何写回刚刚读取的csv文件(c++)
- c++filt可以用来将解映射的名称写回.s文件本身吗
- 尝试在c++中使用函数对TXT文件进行排序并将其写回TXT文件
- 如何将JSON写回文件
- C++中的文件I/O-在写回数据时遇到一些问题
- 从cin读取两个字符串并将其写回时出现意外行为
- 读取CSV数据,并在某些列添加双引号,然后重新写回文件