plz some 1 help me i stuck in this code

//heder file??test.h
#ifndef TEST_H
#define TEST_H
#include "stdafx.h"
class test
{
public:
char a[200],b[200];
int i,len;
void readdata(void);
void writedata(void);
void revarray(void);
};
#endif // TEST_H


//test.cpp
#include "stdafx.h"
#include<iostream>
#include<fstream>
#include<string.h>
#include"test.h"
using namespace std;
void test::readdata()
{
ifstream read("atc.text");
read.is_open();
read.getline(a,200);
len=strlen(a);
cout<<"the data is \n"<<a;
read.close();
}
void test::revarray()
{
for(i=len-1;i>=0;i--)
{
b[(len-i)-1]=a[i];
cout<<a[i];
}
cout<<"\n\n";
}
void test::writedata()
{
ofstream write;
write.open("atc2.text");
write<<b;
write.close();
}

//main.cpp
#include "stdafx.h"
#include "test.h"
int _tmain(int argc, _TCHAR* argv[])
{

test data;
data.readdata();
data.revarray();
data.writedata();
return 0;
}


the problem in this code is i want to read from a atc.text file as
kamal
Manav
Abhishek
united
//then reverse the readen data like
lamak
vanam
kehsihbA
detinu
then write these lines in text2 file..

i found the output by this code in atc2 file like lamakIIIIIIIyyyyyyy this type and some garbage...
Last edited on
While reversing the array from a to b the character locations of array b are incorrectly calculated and all 200 char of array are being dumped into the output file.

For example: In void test::revarray() function.

when len = 5 : i = 4 & the index of array b will be [( 5 - 4 ) - 4], this would return the negative number (-3) which is incorrect.

you would have to change the logic [(len-i)-i]
Last edited on
here [(len-i)-1] insteed of [(len-i)-1]

what is the logic for memset command

if i applied before wring the b array then i got null at array b using memset command
you can modify revarray() function to:

1
2
3
4
5
6
7
8
9
10
void test::revarray()
{
	for(i=len-1;i>=0;i--)
	{
		b[len - i%len - 1]=a[i];
		cout<<a[i];
	}
	b[len] = '\0'; // to push the string truncation symbol.
	cout<<"\n\n";
}

closed account (zb0S216C)
Why are you over-complicating the index?

1
2
3
4
5
for(int index_b(len - 1), index_a(0); index_b >= 0; --index_b, ++index_a)
{
    b[index_a] = a[index_b];
    std::cout << b[index_a];
}

Edited!

Wazzak
Last edited on
Yeah, either way works!

But here too you would require b[len] = '\0'; at the end to suppress the garbage.
void test::revarray()
{
for(i=len-1;i>=0;i--)
{
b[len - i%len - 1]=a[i];
cout<<a[i];
}
b[len] = '\0'; // to push the string truncation symbol.
cout<<"\n\n";
}

thank u all of you this logic working as i want the output thank u very much all of u thanx a lot.....
Topic archived. No new replies allowed.