以下是我必须进行更改的文件(as-1.txt
)。应该as-1
而不是as-2
。
此代码生成as-1.txt
的副本,并且还更改该文件的内部数据。如果文件中的文件名为as-2
,则as-1
也应更改为as-2
。
我已完成复制部分但无法更改文件数据:
示例输入:
&cntrl
pTopt = 298.15, pdens = 0.997, prcut = 12.0, pion = t,
pihot = t, prQM = 5.5, prSM = 5.3, prQI=3.0, piguess = f,
pinit = t, pnstep = 5000, pnscale = 100,
pnstat = 5, pnout = 5, pnrst = 5, pioutc = t, pioutv = t, pnoutc = 5, pnoutv = 5,
msolute = t, nosa = 1, pichrg = t
gfileOut = 'as-1.out',
gfileEnout = 'as-1.en',
gfileInfo = 'as-1.info',
gfileStart = 'init.in',
gfileRst = 'as-1.rst',
gfileTraj = 'as-1.traj',
gfileVeloc = 'as-1.vel',
gfileQmen = 'as-1.qmen'
&end
我的代码:
#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "windows.h"
#include "stdio.h"
#include "string"
using namespace std;
void main()
{
string str;
ifstream myfile("as-1.txt");// for reading a file
char j = '2';
if (!myfile)// if file not present
{
cerr << "file not opening";//cerr is for displaying errors
exit(1);
}
for (int i = 0; i < 9; i++)// for multiple copies
{
char name[9] = { 'a', 's', '-', j,'.','t','x','t' ,'\0'};// for setting file name , j increments
ofstream myfile1(name);// to write on file
cout << name<<endl;
while (!myfile.eof())// run till end of file
{
getline(myfile,str); // get line by line text from myfile
myfile1 << str << endl;// insert line fetched from myfile to myfile 1
}
j++;// to increment in ascii code
myfile.clear();// to clear end of file(eof)
myfile.seekg(0, ios::beg);//take cursor to begining of file
}
system("pause");
}
答案 0 :(得分:0)
要替换您,可以使用std::string
的{{3}}方法,但您需要知道要替换的字符范围(找到它使用find
方法)。我在这个replace
找到了很好的方法。另外最好使用std::string
并且不要将其与char
和char
数组混淆,因此要将int
转换为std::string
我使用了另一个as-10.txt
3}},或者你可以简单地使用answer,如果你可以接受的话。
所以这里是完整代码,它将创建9个新文件as-2.txt
,as-3.txt
,as-4.txt
,as-5.txt
,as-6.txt
,as-7.txt
,as-8.txt
,as-9.txt
和#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
namespace patch {
template< typename T >
std::string to_string( const T& n ) {
std::ostringstream stm;
stm << n;
return stm.str();
}
}
using namespace std;
void replace_all(string& str, const string& from, const string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
int main(int argc, char** argv) {
ifstream myfile("as-1.txt");
if(!myfile) {
cerr << "Could not open file " << "as-1.txt\n";
return 1;
}
for(int i = 0; i < 9; i++) {
string name = "as-" + patch::to_string(i + 2) + ".txt";
ofstream myfile1(name.c_str());
if(!myfile1) {
cerr << "Could not open file " << name << "\n";
return 1;
}
cout << name<<endl;
string line;
while(!myfile.eof()) {
getline(myfile, line);
replace_all(line, "as-1", "as-" + patch::to_string(i + 2));
myfile1 << line << endl;
}
myfile.clear();
myfile.seekg(0, ios::beg);
}
return 0;
}
。
NSURLConnection