lundi 23 février 2015

Very Simple C Strings: Storing and printing a string in a struct in C

I have a struct which I would like to store a string in:



#define MAXLINE 80

struct HistoryElement
{
int NumberOfCommandGiven;
char command[MAXLINE];
};


As you can see, the array of characters called command is meant to store the string.


However, I am having trouble when trying to store such a string in a struct.



struct HistoryElement* History = malloc(historysize*sizeof(struct HistoryElement)); //Create an array of HistoryElements
char iBuffer[MAXLINE];
char *args[MAXLINE/2+1];
setup(iBuffer, args, &bgrnd); //Parses input string into iBuffer and args
//Add the command to history:
struct HistoryElement input;
input.NumberOfCommandGiven = numberofcommand; //this works fine.
strcpy(input.command, iBuffer); //<-- This is what must be wrong!
printf("input.command: %s",input.command); //***TEST***
History[numberofcommand-1%historysize] = input;


The TEST case will only print the first word of any string, it does not include spaces. So if the input command was "ls -l", then the test case will only print out "ls", whereas it should print "ls -l". Why is it not picking up the entire line that is input by the user?


Aucun commentaire:

Enregistrer un commentaire