Thread: writing char arrays to a file

  1. #1
    Registered User
    Join Date
    Apr 2003
    Posts
    9

    writing char arrays to a file

    I've got 2 char arrays as follows:

    password[80];

    message[80];


    I want to write them to a file ONE AT A TIME. First the password onto the 1st line of the file. Then the message onto the second line of the file.

    I've tried the following with put(). The program crashes. I also tried write()

    e.g. outfile.write(password,80); This crashes too.

    Code:
        i = 0;
    	while(password[i] != '\0')
    	{
    		fout.put(password[i]);
    		i++;
    	}
    
    
    AND
    
        i = 0;
    	while(message[i] != '\0')
    	{
    		fout.put(message[i]);
    		i++;
    	}

    Help please?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Help please?
    Perhaps:
    Code:
    fout<< password <<'\n'<< message <<flush;
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Although I would recommend the method Prelude suggested, write() and put() do work:
    Code:
    #include <fstream>
    using namespace std;
    
    int main()
    { 
    	char text[5]="hi";
    
    	ofstream outFile("C:\\TestData\\output.txt");
    	int i =0;
    
    	while(text[i] != '\0')
    	{		
    		outFile.put(text[i]);
    		i++;
    	}
    
    	
    	char word[10]="world";
    	
    	outFile.put('\n');
    	outFile.write(word, 10);
    
    	return 0;
    }
    Output:
    hi
    world

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can we have vector of vector?
    By ketu1 in forum C++ Programming
    Replies: 24
    Last Post: 01-03-2008, 05:02 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  4. Program Crashing
    By Pressure in forum C Programming
    Replies: 3
    Last Post: 04-18-2005, 10:28 PM
  5. Writing to a Binary File
    By Lah in forum C Programming
    Replies: 1
    Last Post: 10-27-2003, 01:41 AM