gpt4 book ai didi

c - 将字符串输入存储到C中的不同数组中

转载 作者:太空宇宙 更新时间:2023-11-04 04:21:29 24 4
gpt4 key购买 nike

你好,这个全新的 C 语言新手正在尝试获取 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;

}


}

如有帮助,万分感谢

最佳答案

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

应该是

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

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

关于c - 将字符串输入存储到C中的不同数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46394720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com