2015-02-24 30 views
0
打印字符串的结构

我有我想一个字符串存储在一个结构:非常简单的C字符串:存储和使用C

#define MAXLINE 80 

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

正如你所看到的,字符数组称为命令是为了存储字符串。

但是,我试图将这样的字符串存储在结构中时遇到了麻烦。

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; 

测试案例将只打印任何字符串的第一个单词,它不包含空格。所以如果输入命令是“ls -l”,那么测试用例只会打印出“ls”,而它应该打印出“ls -l”。为什么不拾取用户输入的整个行?

+2

iBuffer包含什么? (尝试打印) – immibis 2015-02-24 00:07:35

+1

是的我的猜测是'设置'功能做错了事情。调试器显示的是什么(你没有在调试器下运行它) – pm100 2015-02-24 00:08:51

+0

iBuffer仅包含短语“ls”而不是“ls -l” – Musicode 2015-02-24 00:09:32

回答

0

does args []包含nul终止字符串?

然后(如果您决定不修复设置()函数)

那么下面就可以解决问题。

// clear the destination to all NUL chars 
memset(input.command, 0x00, sizeof input.command); 

// loop until a args[i] entry begins with NUL char 
int i; 
while(args[i][0]) 
{ 
    // append args[i] to end of string in input.command 
    strcat(input.command, args[i]); 
    i++; 
} 
+0

这看起来非常类似于我在想什么,我需要什么,让我试试。 – Musicode 2015-02-24 00:47:07

+0

如果你仍然在那里,我会非常感谢这段代码的任何帮助。我正在使用它的段错误,但它看起来非常类似于我想要的。 – Musicode 2015-02-24 00:54:14