im a newbee for this forum and c++ im doing my MSc in Simulation Tech in mech. Engineering. My knowledge of c++ is very little which I had during my UG studies Long long ago .I am now forced to do some programming as a small part of my thesis work. Here goes my task and question.
I want to read the text file and jus find the displacement old value and replace them with new value and write them in another file.........(In my analysis, an input file has been created contains some variables.For ex: a displacement value the the only variable for several analysis which i need to change to perform different analysis)
Jus I made a small program for it by using all my C++ knowledge (!!!!!!!)
To replace 0.000(old value) to 1.413(new value) and write it in another file .
I didn’t use getline () function as it is trying to replace the whole line at once even if there r two values to replace within a line.
I donno whether it is possible using getline function(I didn’t succeed replacing all the values in a line by using it)
Here comes my text file
Samp1.txt: contains
0.000 God save us programmers
I don’t do programming here after 0.000 for sure 0.000
Expand|Select|Wrap|Line Numbers
- #include <fstream>
- #include <iostream>
- #include <string>
- using namespace std;
- int main()
- {
- string a;
- string string1;
- string string2 = "1.413";
- string string3 = "0.000";
- fstream inputFile("C:\\TEMP\\samp1.txt");
- fstream outputFile;
- outputFile.open("C:\\TEMP\\samp2.txt");
- while (!inputFile.eof()) {
- inputFile >> a;
- //cout << a ;
- int spot = a.find(string2);
- if (spot >= 0) {
- cout << "found at" << spot << " the string" << string2 << endl;
- string1 = a;
- int b = string3.length();
- string1.replace(spot, b, string3);
- a = string1;
- cout << a << endl;
- cin.get();
- }
- outputFile << a << endl;
- }
- outputFile.close();
- }
Samp2.txt: written file contains output like
1.413
God
save
us
programmers
I
don’t
do
programming
here
after
1.413
for
sure
1.413
1.413 (****)
1. I want to hav my output file looks the same as my input file (only with a change of value replacement) not like this now I hav
2. while loop executes eof () true value at the end of file and prints again the value “a” (which stored last …. refer output (****))
may b sound simple and sillyfor u, but for me its complex
i want my output looks like
Samp2.txt:
1.413 God save us programmers
I don’t do programming here after 1.413 for sure 1.413
Will you give me some sugesstion to get my output in such a manner?
some new functions or methods?