1

Basically the program should split the name into F and L names. User puts in their name either combined or with a space (ex. AlexTank or Alex Tank). The program should read in every capital letter and split the string with a space. The issue I have is that my program splits the name (recognizes uppercase letters) but excludes the upper case letters from the new output of the string.

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

int main()
{
    char name[50], first[25], last[25];
    char *pch;
    char* key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    // ask user for name
    printf("What is your name? ");
    scanf("%s", name);

    printf("Hello \"%s\" here is your First and Last Name:\n", name);
    pch = strtok(name, key);
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, key );
    }
    return 0;
}
4

2 回答 2

1

有两个问题:

  1. 第二个参数strtok应该只是你想要的分隔符字符串,明确地。就您而言,我认为这只是一个空格(" ")。
  2. 当它看到输入上的空间时停止阅读%sscanf

修改程序:

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

int main()
{
    char name[50], first[25], last[25];
    char *pch;

    // ask user for name
    printf("What is your name? ");
    //scanf("%s", name);
    fgets(name, 50, stdin);

    printf("Hello \"%s\" here is your First and Last Name:\n", name);
    pch = strtok(name, " ");
    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, " ");
    }
    return 0;
}

如果您也想允许 CamelCase 名称,那么strtok它不会单独工作,因为它会破坏分隔符。您可以做一些简单的事情,例如预处理名称并插入空格,或者编写自定义标记器。这是插入空间的想法方法。如果你只是插入空格,那么strtok就会做你想做的事:

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

void insert_spaces(char *in, char *out)
{
    if ( !in || !out )
        return;

    while ( *in )
    {
        if (isupper(*in))
            *out++ = ' ';

        *out++ = *in++;
    }

    *out = '\0';
}

int main()
{
    char in_name[50], first[25], last[25];
    char name[100];
    char *pch;

    // ask user for name
    printf("What is your name? ");
    //scanf("%s", name);
    gets(in_name);

    printf("Hello \"%s\" here is your First and Last Name:\n", in_name);

    insert_spaces(in_name, name);

    pch = strtok(name, " ");

    while (pch != NULL)
    {
        printf("%s\n", pch);
        pch = strtok(NULL, " ");
    }
    return 0;
}
于 2013-10-15T19:41:19.953 回答
0

strtok假设您不希望返回分隔符 - 因此它将消耗它们并返回“其余部分”(即仅小写字母)。我建议一种更简单的方法:一次回显输入字符串一个字符;如果您看到一个大写字母但不只是看到一个空格,请将其添加进去。它看起来像这样:

#include <stdio.h>

int main()
{
    char name[50];

    // ask user for name
    printf("What is your name? ");
    //scanf("%s", name);
    fgets(name, 49, stdin);

    printf("Hello. Your name is ");
    int ii = 1, foundSpace = 0;
    printf("%c", name[0]);
    while (name[ii] != '\0')
    {
        if (name[ii]==' ') foundSpace = 1;
        if (foundSpace == 0 && isupper(name[ii])) {
          printf(" %c", name[ii]);
        }
        else {
          putchar(name[ii]);
          foundSpace = 0;
        }
        ii++;
    }
    return 0;
}

看看这是否适合你!

于 2013-10-16T03:13:45.413 回答