在C语言中将字符串输入存储到不同的数组中

在C语言中将字符串输入存储到不同的数组中,c,arrays,string,char,C,Arrays,String,Char,您好,这个全新的C上的noob正在尝试获取3个单词的字符串输入,并将其存储在3个不同的数组中,而不是2D或3D数组。对于这个问题,我不允许使用任何字符串库函数。基本上,我正在尝试实现sscanf函数。我创建了一个函数,将输入分成三个字,并将它们存储在指定的数组中。我的问题是,当我试图打印每个数组时,对于我的第二个数组,我无法让它打印我试图存储在其中的单词。我可能没有储存任何东西,但我找不到我的错误。这就是我所拥有的 #include<stdio.h> #include<stri

您好,这个全新的C上的noob正在尝试获取3个单词的字符串输入,并将其存储在3个不同的数组中,而不是2D或3D数组。对于这个问题,我不允许使用任何字符串库函数。基本上,我正在尝试实现sscanf函数。我创建了一个函数,将输入分成三个字,并将它们存储在指定的数组中。我的问题是,当我试图打印每个数组时,对于我的第二个数组,我无法让它打印我试图存储在其中的单词。我可能没有储存任何东西,但我找不到我的错误。这就是我所拥有的

#include<stdio.h>
#include<string.h>


void breakUp(char *, char *, char *, char *, int* );
int main()
{
 char line[80], comm[10], p1[10], p2[10];
 int len, n=0;

 printf("Please Enter a command: ");

 fgets(line, 80, stdin);

/* get rid of trailing newline character */
len = strlen(line) - 1;
if (line[len] == '\n')
    line[len] = '\0';

/* Break up the line */
breakUp(line, comm, p1, p2, &n);

printf ("%d things on this line\n", n);
printf ("command: %s\n", comm);
printf ("parameter 1: %s\n", p1);
printf ("parameter 2: %s\n", p2);

return 0;
}

/*
 This function takes a line and breaks it into words.
The orginal line is in the char array str, the first word
will go into the char array c, the second into p1, and the
the third into p2.  If there are no words, the corresponding
char arrays are empty.  At the end, n contains the number of
words read.
*/
void breakUp(char *str, char *c, char *p1, char *p2, int* n)
{
c[0] = p1[0] = p2[0] = '\0';
p1[0] = '\0';
int j = 0; // str array index
int i = 0; // index of rest of the arrays
n[0] = 0;

// stores first word in array c
while(str[j]!= ' '|| str[j] == '\0')
  {
      c[i]= str[j];
      i++;
      j++;
  }
// increases n count, moves j into next element
// and sets i back to index 0
if (str[j] == ' '|| str[j] == '\0')
  {
     c[i] = '\0';
      n[0]++;
      j++;
      i =0;
      if( str[j] == '\0')
          return;
  }

// stores second word in array p1
while(str[j]!= ' '|| str[j] == '\0')
{
    p1[i]= str[j];
    i++;
    j++;
}
// increases n count, moves j into next element
// and sets i back to index 0
if (str[j] == ' '|| str[j] == '\0')
{
    p1[i] = '\0';
    n[0]++;
    j++;
    i =0;
    if( str[j] == '\0')
        return;
}

// stores 3rd word in array p2
while(str[j] != ' ' || str[j] == '\0')
  {
      p2[i] = str[j];
      i++;
      j++;
  }
// increases n count, moves j into next element
// and sets i back to index 0
if(str[j] == ' ' || str[j] == '\0')
  {
      p2[i] = '\0';
      n[0]++;
      if( str[j] == '\0')
          return;

  }


}
#包括
#包括
无效分解(char*,char*,char*,char*,int*);
int main()
{
字符行[80]、comm[10]、p1[10]、p2[10];
int len,n=0;
printf(“请输入命令:”);
fgets(第80行,标准DIN);
/*去掉尾随的换行符*/
len=strlen(线)-1;
如果(行[len]='\n')
行[len]='\0';
/*分队*/
分解(线路、通信、p1、p2和n);
printf(“%d事物在此行\n”,n);
printf(“命令:%s\n”,comm);
printf(“参数1:%s\n”,p1);
printf(“参数2:%s\n”,p2);
返回0;
}
/*
此函数获取一行并将其拆分为单词。
原始行位于char数组str中,第一个字
将进入字符数组c,第二个进入p1,然后
第三个是p2。如果没有单词,对应的
字符数组为空。最后,n包含
读单词。
*/
无效分解(char*str、char*c、char*p1、char*p2、int*n)
{
c[0]=p1[0]=p2[0]='\0';
p1[0]='\0';
int j=0;//str数组索引
int i=0;//其余数组的索引
n[0]=0;
//在数组c中存储第一个字
while(str[j]!=''| str[j]=='\0')
{
c[i]=str[j];
i++;
j++;
}
//增加n计数,将j移到下一个元素
//并将i设置回索引0
如果(str[j]=''| | str[j]='\0')
{
c[i]='\0';
n[0]++;
j++;
i=0;
如果(str[j]='\0')
返回;
}
//在数组p1中存储第二个字
while(str[j]!=''| str[j]=='\0')
{
p1[i]=str[j];
i++;
j++;
}
//增加n计数,将j移到下一个元素
//并将i设置回索引0
如果(str[j]=''| | str[j]='\0')
{
p1[i]='\0';
n[0]++;
j++;
i=0;
如果(str[j]='\0')
返回;
}
//在数组p2中存储第三个字
while(str[j]!=''| str[j]=='\0')
{
p2[i]=str[j];
i++;
j++;
}
//增加n计数,将j移到下一个元素
//并将i设置回索引0
如果(str[j]=''| | str[j]='\0')
{
p2[i]='\0';
n[0]++;
如果(str[j]='\0')
返回;
}
}
如果提供任何帮助,请提前感谢

while(str[j]!= ' '|| str[j] == '\0')
应该是

while(str[j]!= ' '&& str[j]!= '\0')
检查是否到达行尾的if语句也是如此。谢谢

应该是

while(str[j]!= ' '&& str[j]!= '\0')

检查是否到达行尾的if语句也是如此。谢谢

除了评论和回答之外,还有一些方面你可能会让自己的事情变得更困难。首先,让我们看看《分手》的回归。为什么要使用
void
?如果您需要能够衡量函数的成功/失败,请选择一个有意义的返回类型,以提供该信息。在这里,只需返回
int
即可(而且它还可以防止必须传递指向
n
的指针进行更新——您可以简单地返回
n
),您可以自由地传递指向
n
的指针,只需注意,它不能用于在调用
breakup
时提供成功/失败信息。返回
n
可以

<>(>:/Cult>代码> BuffoS/<代码>全部为小写-将CAMECASE变量java和C++,C传统上使用所有小写变量和函数名保留所有大写的常量和宏)

其次,避免在代码中使用幻数(例如,
80
10
,等等)。如果需要常量,则在顶部定义它们,或使用枚举定义全局常量。这样,您就可以在文件的顶部找到一个方便的位置来进行调整,而不必仔细检查每个字符数组声明,如果需要更改数组大小等,则可以更改幻数。例如,要定义字数、命令数组长度和行缓冲区长度,您可以简单地执行以下操作:

#define NWRD 3      /* number of words */
#define CLEN 16     /* command length  */
#define LLEN 80     /* line buffer len */
或使用枚举:

enum { NWRD = 3, CLEN = 16, LLEN = 80 };    /* constants */
现在,对于
breakup
的内容,您可以自由地复制代码块以分别读取每个单词3次,但是您可以更聪明一点,并意识到您已经将指针传递到3个字符数组以
breakup
,为什么不使用初始化为
{c,p1,p2}的指针数组呢
然后只写一段代码,从
str
中挑出每个单词?可以说,这只是给猫剥皮的一种较短的方法。这样,您就不必引用
c,p1,p2
,只需在
arr[0],arr[1],arr[2]
上循环,其中
arr[0]=c,arr[1]=p1,arr[2]=p2

例如,如果您的新声明是
分手

int breakup (char *str, char *c, char *p1, char *p2);
breakup
中,可以按如下方式分配指针数组:

    char *arr[] = { c, p1, p2 };
然后,您可以简单地将第一个单词中的所有字符添加到
arr[0]
,将第二个单词中的所有字符添加到
arr[1]
,依此类推,依次填充
c、p1、p2
。这看起来像是可以在一个很好的单循环中处理的东西

您现在需要做的就是找到一种方法,将每个字符添加到每个单词中,检查空格(或多个空格和制表符),确保每个单词都以nul结尾,确保只填充三个单词,不填充更多,最后返回您填充的单词数

不必对每一点进行重复,您可以将
分手
缩短为以下内容:

int breakup (char *str, char *c, char *p1, char *p2)
{
    char *arr[] = { c, p1, p2 };            /* assign c, p1, p2 to arr */
    int cidx = 0, n = 0;                    /* character index & n */

    for (; n < NWRD; str++) {               /* loop each char while n < NWRD */
        if (*str == ' ' || *str == '\t') {  /* have space or tab? */
            if (*arr[n]) {                  /* have chars in arr[n]? */
                arr[n++][cidx] = 0;         /* nul-terminate arr[n] */
                cidx = 0;                   /* zero char index */
            }
        }
        else if (*str == '\n' || !*str) {   /* reached '\n' or end of str? */
            arr[n++][cidx] = 0;             /* nul-terminate arr[n] */
            break;                          /* bail */
        }
        else
            arr[n][cidx++] = *str;          /* assign char to arr[n] */
    }

    return n;
}
#include <stdio.h>

enum { NWRD = 3, CLEN = 16, LLEN = 80 };    /* constants */

int breakup (char *str, char *c, char *p1, char *p2)
{
    char *arr[] = { c, p1, p2 };            /* assign c, p1, p2 to arr */
    int cidx = 0, n = 0;                    /* character index & n */

    for (; n < NWRD; str++) {               /* loop each char while n < NWRD */
        if (*str == ' ' || *str == '\t') {  /* have space or tab? */
            if (*arr[n]) {                  /* have chars in arr[n]? */
                arr[n++][cidx] = 0;         /* nul-terminate arr[n] */
                cidx = 0;                   /* zero char index */
            }
        }
        else if (*str == '\n' || !*str) {   /* reached '\n' or end of str? */
            arr[n++][cidx] = 0;             /* nul-terminate arr[n] */
            break;                          /* bail */
        }
        else
            arr[n][cidx++] = *str;          /* assign char to arr[n] */
    }

    return n;
}

int main (void) {

    char line[LLEN] = "", comm[CLEN] = "", p1[CLEN] = "", p2[CLEN] = "";
    int n = 0;

    printf ("please enter a command: ");    /* prompt & get line */
    if (!fgets (line, LLEN, stdin) || !*line || *line == '\n') {
        fprintf (stderr, "error: input empty or user canceled.\n");
        return 1;
    }

    if ((n = breakup (line, comm, p1, p2)) != NWRD) {   /* call breakup */
        fprintf (stderr, "error: %d words found\n", n);
        return 1;
    }

    printf ("command    : %s\nparameter 1: %s\nparameter 2: %s\n",
            comm, p1, p2);

    return 0;
}
注意:
#include <stdio.h>

enum { NWRD = 3, CLEN = 16, LLEN = 80 };    /* constants */

int breakup (char *str, char *c, char *p1, char *p2)
{
    char *arr[] = { c, p1, p2 };            /* assign c, p1, p2 to arr */
    int cidx = 0, n = 0;                    /* character index & n */

    for (; n < NWRD; str++) {               /* loop each char while n < NWRD */
        if (*str == ' ' || *str == '\t') {  /* have space or tab? */
            if (*arr[n]) {                  /* have chars in arr[n]? */
                arr[n++][cidx] = 0;         /* nul-terminate arr[n] */
                cidx = 0;                   /* zero char index */
            }
        }
        else if (*str == '\n' || !*str) {   /* reached '\n' or end of str? */
            arr[n++][cidx] = 0;             /* nul-terminate arr[n] */
            break;                          /* bail */
        }
        else
            arr[n][cidx++] = *str;          /* assign char to arr[n] */
    }

    return n;
}

int main (void) {

    char line[LLEN] = "", comm[CLEN] = "", p1[CLEN] = "", p2[CLEN] = "";
    int n = 0;

    printf ("please enter a command: ");    /* prompt & get line */
    if (!fgets (line, LLEN, stdin) || !*line || *line == '\n') {
        fprintf (stderr, "error: input empty or user canceled.\n");
        return 1;
    }

    if ((n = breakup (line, comm, p1, p2)) != NWRD) {   /* call breakup */
        fprintf (stderr, "error: %d words found\n", n);
        return 1;
    }

    printf ("command    : %s\nparameter 1: %s\nparameter 2: %s\n",
            comm, p1, p2);

    return 0;
}
$ ./bin/breakup
please enter a command: dogs have fleas
command    : dogs
parameter 1: have
parameter 2: fleas

$ ./bin/breakup
please enter a command: dogs have
error: 2 words found

$ ./bin/breakup
please enter a command: dogs have lots of fleas
command    : dogs
parameter 1: have
parameter 2: lots

$ ./bin/breakup
please enter a command: dogs    have       fleas   for    sale
command    : dogs
parameter 1: have
parameter 2: fleas