C 编程-拆分函数但最后一个字母被切断?

C Programming- Splitting a function but last letter is being cut off?

所以我正在尝试为我所在的 class 做一个编码项目,我们需要拆分像 ATL1234S15 这样的代码,我能够让第一部分大部分工作,除了它会只打印 AT 而不是 ATL?

这是我的代码,如有任何帮助,我们将不胜感激。

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

void main(void)
{
    char Code[30];
    char Piece[10];
    int token = 0;

    printf("Enter a product code: ");
    scanf("%s", Code);

    for (token = 0; !(Code[token] >= '0' && Code[token] <= '9'); token++)
    {
        strcpy(Piece, Code);
        Piece[token] = '[=10=]';
    }
    printf("Warehouse: %s ", Piece);

您的代码目前有一个小错误导致了这个问题。

您将字母“T”替换为“\0”,因为代码:Piece[token] = '[=11=]'; 您应该在字母 T 后添加“\0”。

更正后的代码是:

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

int main(int)
{
    char Code[30];
    char Piece[10];
    int token = 0;

    printf("Enter a product code: ");
    scanf("%s", Code);

    for (token = 0; !(Code[token] >= '0' && Code[token] <= '9'); token++)
    {
        strcpy(Piece, Code);
        Piece[token+1] = '[=10=]';
    }
    printf("Warehouse: %s ", Piece);
    return 0;
}

我还建议您将迭代器用作“i”,而不是“token”。我相信你会更容易阅读和理解代码。

您不应该在循环中复制字符串。您可以使用“isdigit”来测试字符,并使用 strncpy 只复制您需要的字符串部分。

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

void main(void)
{
    char Code[30];
    char Piece[10];
    int i = 0;
    
    printf("Enter a product code: ");
    scanf("%29s", Code);

    while (!isdigit(Code[i++]))
        ;   // Loop until a digit is found
    strncpy(Piece, Code, i);
    Piece[i] - '[=10=]';
    printf("Warehouse: %s ", Piece);
}