在c++中替换文本行中的某个值
replace some value in text line in c++
大家好,我用这段代码来查找包含seta r_fullscreen "0"
的行,如果这一行的值是0,则返回MessageBox,但我的问题是,如果seta r_fullscreen
的值是"0",那么我如何将这一行中的值替换为"1"?
ifstream cfgm2("players\config_m2.cfg",ios::in);
string cfgLine;
Process32First(proc_Snap , &pe32);
do{
while (getline(cfgm2,cfgLine)) {
if (string::npos != cfgLine.find("seta r_fullscreen")){
if (cfgLine.at(19) == '0'){
MessageBox(NULL,"run in full Screen mod.","ERROR", MB_OK | MB_ICONERROR);
...
您可以使用std::string::find()
和std::string::replace()
来执行此操作。找到包含配置说明符seta r_fullscreen
的行后,可以执行以下操作。
std::string::size_type pos = cfgLine.find(""0"");
if(pos != std::string::npos)
{
cfgLine.replace(pos, 3, ""1"");
}
您不应该假设配置值"0"
处于特定偏移,因为r_fullscreen
和"0"
之间可能存在额外的空格。
在看到您的附加注释后,您需要在进行更改后更新配置文件。对字符串所做的更改仅适用于内存中的副本,不会自动保存到文件中。您需要在加载和更改每一行后保存它,然后将更新保存到文件中。您还应该将更新配置文件的过程移到do/while
循环之外。如果你不这样做,你会阅读/更新你检查的每个过程的文件。
下面的例子应该让你开始。
#include <fstream>
#include <string>
#include <vector>
std::ifstream cfgm2("players\config_m2.cfg", std::ios::in);
if(cfgm2.is_open())
{
std::string cfgLine;
bool changed = false;
std::vector<std::string> cfgContents;
while (std::getline(cfgm2,cfgLine))
{
// Check if this is a line that can be changed
if (std::string::npos != cfgLine.find("seta r_fullscreen"))
{
// Find the value we want to change
std::string::size_type pos = cfgLine.find(""0"");
if(pos != std::string::npos)
{
// We found it, not let's change it and set a flag indicating the
// configuration needs to be saved back out.
cfgLine.replace(pos, 3, ""1"");
changed = true;
}
}
// Save the line for later.
cfgContents.push_back(cfgLine);
}
cfgm2.close();
if(changed == true)
{
// In the real world this would be saved to a temporary and the
// original replaced once saving has successfully completed. That
// step is omitted for simplicity of example.
std::ofstream outCfg("players\config_m2.cfg", std::ios::out);
if(outCfg.is_open())
{
// iterate through every line we have saved in the vector and save it
for(auto it = cfgContents.begin();
it != cfgContents.end();
++it)
{
outCfg << *it << std::endl;
}
}
}
}
// Rest of your code
Process32First(proc_Snap , &pe32);
do {
// some loop doing something I don't even want to know about
} while ( /*...*/ );
相关文章:
- 文本文件中的单词链表
- 从命令行c++发送文本文件名
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何将内容数组写入文本文件?
- 无法通过空白将文本文件行分隔为矢量
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- C++将文本文件中的数据读取到结构数组中
- 在指针的帮助下,文本文件中单词的频率
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 将值从二维数组输出到文本文件
- 如何在c++中从文本文件中逐行读取整数
- 如何创建一个QTableWidgetItem,用长文本右对齐,左边有省略号
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何根据单词在文本中出现的概率输出单词
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- C++试图读取一个文件并输出到另一个文本文件
- 如何通过套接字将文本文件的内容从服务器发送到客户端