【问题标题】:Writing each word with pointer array用指针数组写入每个单词
【发布时间】:2016-03-18 13:42:35
【问题描述】:

我有一个拆分单词的程序。就像如果我写“我的名字是阿里” 程序会写

Word one: My
Word two: name
word three: is
word four: ali

现在我想添加类似的东西

int number;
printf("which word do you want to write? number: \n");
scanf("%d",&number)

然后如果用户写“四”,则假设写ali 或者如果他们写“二”,则应该写为name

int delaUppText(char input[], char* pekare[])
{
    int i=0, j=0;
    char prevLetter=' ';

    for(i=0; input[i]!=NULL; i++)
    {
        if(prevLetter==' '&&input[i]!=' ')
        {
            pekare[j]=&input[i];
            j++;
        }
        prevLetter=input[i];
    }

    for(i=0; input[i]!=NULL; i++)
    {
        if (input[i] == ' ')
        {
            input[i]=NULL;
        }
    }

    return j;
}

int main()
{
    char input[200];
    char* pekare[100];
    int i, antalPekare;
    char answer = 32;
    int nummer;

    do
    {
        system("cls");
        printf("Enter a string: ");

        gets(input);

        printf("\n");

        antalPekare = delaUppText(input, pekare);

        for(i=0;i<antalPekare;i++)
        {
            printf("Ord %d: %s\n", i+1, pekare[i]);
        }

        printf("\nWould you like to try again? [Space]/[q]");
        answer = getch();

        if (answer == 32)
        {
         system("cls");
        }
        else if (answer == 'q')
        {
            break;
        }
    }while (answer == 32);

    return 0;
}

【问题讨论】:

  • 假设您投了反对票,请留言说明原因。我真的不明白为什么这个问题应该被否决。
  • 有什么问题? OP 尝试了什么?

标签: c


【解决方案1】:

不幸的是编译器不会说英语。

因此,如果您的用户必须输入“四”,那么不要指望scanf("%d",&amp;number) 会识别“四”这个词。它只能识别数字,因此您的用户必须输入“4”,或者您必须解析输入以了解他输入的数字字。用德语输入怎么样?

【讨论】:

    【解决方案2】:

    1

    查看您的代码,我发现有很多更好的方法可以做到这一点。 其中一种方法是使用 strtok,您可以在此处找到有关它的更多信息。

    #include <string.h>
    char *strtok(char *str, const char *delim);
    char *strtok_r(char *str, const char *delim, char **saveptr);
    

    http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

    或者你也可以使用 strsep

    #include <string.h>
    char *strsep(char **stringp, const char *delim);
    

    2

    现在,如果你想让它与你所拥有的一起工作。您需要使用堆内存。又名 [malloc, calloc]。原因是一旦您返回主程序,程序的堆栈将减少,并且曾经在您的程序中的堆栈上的内存将不再存在。 现在,如果您使用堆,那么您还应该确保只释放一次内存。

    对于剩下的问题,我将让您阅读本文。

    In C/C++, is char* arrayName[][] a pointer to a pointer to a pointer OR a pointer to a pointer?

    【讨论】:

      猜你喜欢
      • 2018-10-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-24
      • 2017-08-23
      • 2020-12-22
      • 2022-09-27
      • 1970-01-01
      • 2011-05-20
      相关资源
      最近更新 更多