Strings and Strucs

This is a discussion on Strings and Strucs within the C Programming forums, part of the General Programming Boards category; It may be because its so late but I've started re-reading up on C and i've been messing around with ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    17

    Strings and Strucs

    It may be because its so late but I've started re-reading up on C and i've been messing around with structures and writing to files. Anyway I've been trying to save some structures to a file and they all work fine except for my char array =-(. Any help would be really awsome on the matter.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    struct Player{
           char name[100];
           int hp;
           int attack;
    };
           
    
    int main(){
        //define all new Structures
        struct Player player;
        struct Player *playerPtr;
        
        //Make all file readers + writers
        FILE *PlayerSave;
        PlayerSave = fopen("C:\\Users\\Adam Flax\\Documents\\test.txt", "r+");
        
        player.name = "hello";
        player.hp = 19;
        player.attack = 17;
        playerPtr = &player;
        
        fprintf(PlayerSave,"%d\n", playerPtr -> name);
        fprintf(PlayerSave,"%d\n", playerPtr -> hp);
        fprintf(PlayerSave,"%d\n", playerPtr -> attack);
        
        fclose(PlayerSave);
        return(0);
    }
    thanks
    zidsal

    p.s
    but ya I have not touched a programming language and its proberly something really stupid like player.name[0] ="hello"; (yes I have tried the obvoius).

  2. #2
    Nor
    Nor is offline
    h ֆhr s Nor's Avatar
    Join Date
    Nov 2001
    Posts
    299
    Is the program not compiling?
    I don't think you can
    Code:
    player.name = "hello";
    try
    Code:
    strncpy(&player.name[0], "hello", sizeof(player.name));
    Try to help all less knowledgeable than yourself, within
    the limits provided by time, complexity and tolerance.
    - Nor

  3. #3
    Registered User
    Join Date
    Sep 2008
    Posts
    58
    Code:
        fprintf(PlayerSave,"%d\n", playerPtr -> name);
    Should that be a string?

  4. #4
    Registered User
    Join Date
    Jan 2008
    Posts
    17
    thanks alot guys, I would of never realised I was using "%d" instead of "%s"

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21