gpt4 book ai didi

c - c 中的二维字符数组未正确写入

转载 作者:行者123 更新时间:2023-11-30 19:42:03 26 4
gpt4 key购买 nike

我是 C 编程新手,还不太习惯没有字符串。下面的代码会将第一个单词正确写入 Arguments[0] 中,但所有其他单词都不会正确写入,我不知道为什么。有人可以帮助我吗?

#include <stdio.h>
#include <stdbool.h>

int main(int argc, int **argv)
{
/*Get input and store it in str*/
char str[100];
if( fgets(str, 100, stdin) != NULL)
{

}
else
{
perror("Null input");
}

/*Parse input into separate arguments*/
int numArg = 0;
int wordStart = 0;
int wordEnd = 0;
bool wordStarted = false;
char Arguments[30][100];
/*iterate through str*/
for(int i =0; i < 100; i++)
{
/*if we're reading a character that isn't a space and we aren't parsing a word yet*/
/*required special case for beginning of input not being a space*/
if(i==0 && str[i] != ' ' || str[i] != ' ' && wordStarted == false)
{
/*set this spot in array to be the start of a word*/
wordStart = i;
/*set boolean so that we are parsing a word*/
wordStarted = true;
}
/*if we're parsing a word, and we see a space or see the line end*/
else if(str[i] == ' ' && wordStarted == true || str[i] == '\n')
{
/*set this spot in array to be the end of a word*/
wordEnd = i;
/*put word into *Arguments*/
for(int k = 0; k < (wordEnd - wordStart); k++)
{
Arguments[numArg][k+wordStart] = str[k+wordStart];
}
/*add null character to end*/
Arguments[numArg][k+wordStart] = '\0';
/*increase number of arguments by 1*/
numArg++;
/*set boolean so that we are no long parsing a word*/
wordStarted = false;
}
}
printf("numArg is %d\n", numArg);
int j = 0;
for(j; j < numArg; j++)
{
printf("Argument %d is: %s\n", j, Arguments[j]);
}
}

如果我运行此代码然后输入:

there are four words

输出将是:

numArg is 4
Argument 0 is: there
Argument 1 is:
Argument 2 is:
Argument 3 is:`

我不明白为什么输出不是:

numArg is 4
Argument 0 is: there
Argument 1 is: are
Argument 2 is: four
Argument 3 is: words

最佳答案

尝试一下,并尝试理解代码并查看为什么您的代码无法工作,因为有多种原因,我认为向您展示一个简单的工作实现会更有帮助

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

int main(int argc, char **argv)
{
char *last;
char *pointer;
char text[100];
int count;
char words[30][100];

if ((pointer = fgets(text, sizeof(text), stdin)) == NULL)
return -1;
while ((*pointer != '\0') && (isspace((int) *pointer) != 0))
++pointer;
count = 0;
last = pointer;
while (*pointer != '\0')
{
if (isspace((int) *pointer) != 0)
{
size_t length;

length = pointer - last;
memcpy(words[count], last, length);

words[count][length] = '\0';

last = pointer + 1;
count += 1;
}
++pointer;
}

fprintf(stdout, "There are %d words\n\n", count);
for (int i = 0 ; i < count ; ++i)
fprintf(stdout, "\t%d: %s\n", i + 1, words[i]);
}

我不是很小心,所以这可能会有很多问题,但这是一种简单的方法来实现你想要的,例如我可以想到“单词”之间有多个空格,这代码不会正确处理这个问题,但正如前面所说,它或多或少会做你想要的事情。

关于c - c 中的二维字符数组未正确写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899281/

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