Solved Edit a number in txt file using c++

March 18, 2013 at 06:24:21
Specs: Windows 7
Hi, I am still a beginner in c++. I am currently at how to edit a stock level in a text file using c++.
Let say for example this is stored in my text file.

1 cocacola 23
2 sprite 3
3 pepsi 89
4 dr pepper 79

What if I want to change the level of sprite from 3 to any number, let say 10. I manage to display to amend it in the program, but not in the text file.
This is my code

void Stockfile :: stockfilelevel(void)
{
file1.open("test.dat",ios::in|ios::out|ios::binary);
{
for(i=0;i<60;i++)
{
file1>>stockcode3[i]>>productname3[i]>>stocklevel3[i];
cout<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i]<<"\n";
}
cout<<"Please enter the stock code of the product:";
cin>>teststockcode;

for(i=0;i<60;i++)
{
if(teststockcode==stockcode3[i])
{
cout<<productname3[i]<<"\t"<<stocklevel3[i];
cout<<"Please enter an amount to change:";
cin>>stockchange3;
stocklevel3[i]=stockchange3+stocklevel3[i];
cout<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i]<<"\n";

for(i=0;i<60;i++)
{
file1<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i];
cout<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i]<<"\n";


file1.close();
}
}
}

}

}

Any help will be appreciated, thank you


See More: Edit a number in txt file using c++

Report •

#1
March 18, 2013 at 08:45:48
Take a look at seekg(), and you should already know about operator>>().

How To Ask Questions The Smart Way


Report •

#2
March 18, 2013 at 09:10:41
You can't change it directly in the existing file. (What would happen if you changed 3 to 13? There isn't room for that in the existing file.) You simply read each line from the input file, make any changes, and then write the line to a new output file. When you have completed that, and closed both files, delete "test.dat" and rename the new file to "test.dat".

Report •

#3
March 18, 2013 at 10:27:15
✔ Best Answer
Thanks, it is already solved now, I have declared another file variable called file2 on fstream. Then do the same thing open for write using ios::out. This is how I solved my problem.

fstream file1,file2;

file1.open("test.dat",ios::in|ios::out|ios::binary);
file2.open("test.dat",ios::out);

for(i=0;i<60;i++)
{
file2<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i]<<"\n";
cout<<stockcode3[i]<<"\t"<<productname3[i]<<"\t"<<stocklevel3[i]<<"\n";


file1.close();
}
file2.close();


Report •
Related Solutions


Ask Question