Saving text stored in array to a txt file

Sep 2, 2013 at 2:36am
Hi, i'm confused with how to save text stored in an array to a txt file.
can sum1 help me how to save the text in an array to a file/txt file......
Sep 2, 2013 at 3:33am
Hi! Ok, can you post some code to tell us what you have tried so far?

You will probably want to use fstream and iterate through your array and write the contents to the file.
Sep 2, 2013 at 4:19am
Use a loop and output each item.

1
2
3
4
5
std::ostream out( "file.txt" );
const int size = 3;
int array[size] = { 1 , 2 , 3 };

for( int i = 0; i < size; ++i ) out >> array[i];
Sep 2, 2013 at 5:14am
Here's my sample code:

void ReadtoMemory(ifstream& InFile, char Memory[])
{
string line;
int MemIndex = 0;

if (InFile.is_open())
{
while ( InFile.good() )
{
getline (InFile,line);
for(int i = 0; i < line.length(); i++)
{
Memory[MemIndex] = line[i] ;

MemIndex++;
}
}
}
}

void OutputMemoryToFile(char Memory [], ofstream& Out)
{
string line; // a single line from file.
int MemIndex = 0;

if (Out.is_open())
{
int i = 0;
while ( Memory[i] != '\0')
{
Out<<Memory[i];
i++;
}
}
}

void DocumentStatisticsPrint(char Memory[])
{
int NumberWords = 0;
int i = 0;
while ( Memory[i] != '\0')
{
if(Memory[i] == ' ')
NumberWords ++;
cout<<Memory[i];
i++;
}
cout<<endl;
cout<<NumberWords<<" is number of words "<<endl;
cout<<"Number of Characters (Including Spaces)"<<i<<endl;
cout<<"Number of Characters (Excluding Spaces)"<<i - NumberWords <<endl;
}

int main(){

const int MAXNUMCHARS = 100000;
char Memory[MAXNUMCHARS];


ifstream InFile ("InputData.txt");
ofstream Out("OutputData.txt");

ReadtoMemory(InFile, Memory) ;
DocumentStatisticsPrint(Memory);
OutputMemoryToFile(Memory, Out);

InFile.close();
Out.close();


return 0;
}
Sep 2, 2013 at 5:26am
the array is of type char which holds 100000 characters.
is it also possible to insert and delete strings and not chars into the char array.
will there be any conversion and copying done here.
and example code would be appreciated.

Sep 2, 2013 at 5:41am
Why do you have a char array with 100,000 characters? o.O and I believe you have to do like strcpy() to put a string into a char array but that's kind of odd also.
Sep 3, 2013 at 3:53am
What are you trying to do? Where is the problem?
Read this:
http://www.cplusplus.com/search.do?q=using+code+tags

Thanks!
Sep 3, 2013 at 8:24am
Topic archived. No new replies allowed.