c++ - 在没有指针的情况下复制 C 字符串中的单个字符

标签 c++

这是作业:

创建一个包含姓名、年龄和职务的 Cstring 变量。每个领域 由空格分隔。例如,该字符串可能包含“Bob 45 程序员”或任何其他相同格式的姓名/年龄/头衔。只用写一个程序 来自 cstring 的函数(不是类 string )可以提取名称, age 和 title 到单独的变量中。

我从字符串中提取了名称,但我无法获取之后的任何字符。我不能使用指针,因为我们还没有学会,所以没有 strtok。我只需要一个方向,因为我确信有一个功能可以使这更容易。谢谢。

#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char y[] = "taylor 32 dentist";
    char name[25];
    char age[4];
    char title[40];
    int i = 0;
    while (y[i] != ' ')
    {
        while (y[i] != '\0')
        {
            if (y[i] == ' ' || y[i + 1] == '\0')
            {
                break;
            }
            name[i] = y[i];
            i++;
        }
    }
    cout << "Name: " << name << endl
         << "Age: " << age << endl
         << "Title: " << title << endl;
    return 0;
}

已解决:

#include <iostream>
#include <cstring>

using namespace std;

void separate_Variables(char y[], char name[], char age[], char title[]);

void output(char name[], char age[], char title[]);

int main()
{
    char y[] = "taylor 32 dentist";
    char name[25];
    char age[4];
    char title[40];
    separate_Variables(y, name, age, title);
    output(name, age, title);
    return 0;
}

void separate_Variables(char y[], char name[], char age[], char title[])
{
    int i = 0;
    int j = 0;
    while (y[i] != '\0' && y[i] != ' ') {
        name[j++] = y[i++];
    }
    name[j] = '\0';
    j = 0;
    i++;
    while (y[i] != '\0' && y[i] != ' ') {
        age[j++] = y[i++];
    }
    age[j] = '\0';
    j = 0;
    i++;
    while (y[i] != '\0' && y[i] != ' ') {
        title[j++] = y[i++];
    }
    title[j] = '\0';
    j = 0;
}

void output(char name[], char age[], char title[])
{
    cout << "Name: " << name << endl
         << "Age: " << age << endl
         << "Title: " << title << endl;
}

最佳答案

您不需要嵌套循环 - 您只需要一个接一个的三个循环。

循环看起来是一样的:获取第 i 个字符,将其与空格进行比较,然后存储在三个目的地之一。当您看到空格时,将其替换为 '\0',然后继续前往下一个目的地:

int j = 0;
while (y[i] != '\0' && y[i] != ' ') {
    name[j++] = y[i++];
}
name[j] = '\0'; // Add null terminator
j = 0;          // Reset j for the next destination
i++;            // Move to the next character in y[]
... // Do the same thing for age and title

关于c++ - 在没有指针的情况下复制 C 字符串中的单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32343785/

相关文章:

c++ - "augments std"的代码使用什么命名空间?

c++ - CMake 找到了 Boost 但 Make 找不到包含文件

c++ - 在 macOS High Sierra 下使用 Cmake 将 Bonmin 与 "ld: framework not found -lAccelerate"链接时出现问题

c++ - 强制可执行文件进入内存?

c++ - 如何使用 libpq 获取 double 值?

c++ - 在 C++ 中 : why does a constructor get called when an array of objects is declared?

c# - 在 C# 和 C++ 之间共享源文件

c++ - 如何从字符串中删除第一个单词?

c++ - 数组、I/O 文件和标准偏差 (c++)

c++ - 你能在Visual C++中找到一个值的实际数量吗?