Revert a string code is not working
I created a .txt file that I called in.txt. It has the letters: a b c d e.
I put it in the same folder as the c++ code below. I was hoping that I after I compile and run the code, the in.txt file would read: e d c b a.
Unfortunately, it doesn't. Even when I give the ofstream file another name, it does not create another text file. Any idea on what could be causing this?
Code:
#include<iostream>
#include<fstream>
#include <limits>
using namespace std;
void reverse(char a[],int b);
int main(){
int counter=0;
char a[100];
ifstream file1;
file1.open("in.txt");
while(file1.eof()==false){file1>>a[counter++];}
a[counter-1]='/0';
reverse(a,counter-1);
file1.close();
ofstream file2;
file2.open("in.txt");
for(int i;i< counter-1;i++){
file2<<a[i];}
file2.close();
//system("PAUSE");
return 0;
}
//cin.get();
//std::cout << "Press ENTER to continue...";
//std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
void reverse(char a[],int b){
char temp;
for(int i=0;i=b/2;i++){
temp=a[i];
a[i]=a[b-i-1];
a[b-i-1]=temp;}
}
Re: Revert a string code is not working
Didn't you debug your code? :confused:
You have to...
Re: Revert a string code is not working
There are 2 errors with this program. One should have produced a compiler warning about a variable being used without having been initialised. The other is purely program logic. However, if you debug your code using a debugger these would be easy to spot. As VictorN said, you must debug code!
Incidentially, if all you want to do is reverse some text held in a file why have the reverse function? Once you have read it into the array why not just write it back looping the array from end to start?
Re: Revert a string code is not working
My compiler did not warn me about any variable being used without having been initialized. What is this variable?
Also, when I run the code or when I click on the debug button, the console pops out empty with only a cursor that seems to stagnate. I don't know what that means.
And what is the second error with program logic?
Re: Revert a string code is not working
What compiler are you using?
What IDE?
Re: Revert a string code is not working
Quote:
Originally Posted by
math8
My compiler did not warn me about any variable being used without having been initialized. What is this variable?
for(int i;i< counter-1;i++){
Your debugger will show why it hangs, but you need to know how to run it. You need to actually watch the code run, not just press the debug button. If you want a clue, look closely at this line
for(int i=0;i=b/2;i++){
Re: Revert a string code is not working
Quote:
Originally Posted by
VictorN
What compiler are you using?
What IDE?
Dev C++
Re: Revert a string code is not working
I figured out what was wrong. 2 typos. i<=b/2 instead of i=b/2 and
for(int i=0;i< counter-1;i++) instead of for(int i;i< counter-1;i++).
Thanks!