在不带指针的C-string中复制单个字符
Copy single characters in C-string without pointers
赋值:
创建一个包含姓名、年龄和标题的Cstring变量。每个字段由一个空格分隔。例如,字符串可能包含"Bob 45"程序员"或任何其他相同格式的姓名/年龄/头衔。编写一个程序从cstring(不是类string)中提取名称的函数,
我从字符串中提取了名称,但在此之后我遇到了任何字符的麻烦。我不能用指针,因为我们还没学过,所以不能用笔划。我只需要一个方向,因为我确定有一个函数可以使它更简单。谢谢你。
#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] != ' ')
{
if (y[i] == ' ' || y[i + 1] == ' ')
{
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] != ' ' && y[i] != ' ') {
name[j++] = y[i++];
}
name[j] = ' ';
j = 0;
i++;
while (y[i] != ' ' && y[i] != ' ') {
age[j++] = y[i++];
}
age[j] = ' ';
j = 0;
i++;
while (y[i] != ' ' && y[i] != ' ') {
title[j++] = y[i++];
}
title[j] = ' ';
j = 0;
}
void output(char name[], char age[], char title[])
{
cout << "Name: " << name << endl
<< "Age: " << age << endl
<< "Title: " << title << endl;
}
您不需要嵌套循环-您所需要的只是三个循环一个接一个。
循环看起来是一样的:取i
-th字符,将其与空格进行比较,并存储在三个目的地之一。当您看到空格时,将其替换为' '
,并继续到下一个目的地:
int j = 0;
while (y[i] != ' ' && y[i] != ' ') {
name[j++] = y[i++];
}
name[j] = ' '; // 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
外环需要测试' '
内部循环(现在是!= ' '
)可以为每个字段复制。您需要一个单独的索引变量来分隔i表示y,并将它放在字段(fi?)
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 使用strcpy将char数组的元素复制到另一个数组
- 是否可以初始化不可复制类型的成员变量(或基类)
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 复制列表初始化的隐式转换的等级是多少
- QT QOpenGLWidget:如何在不使用数据块复制的情况下修改VBO中的单个顶点值?
- char 数组在上次迭代时复制整个单词而不是单个字母
- 在单个链接列表中实现复制构造函数C
- 为什么为单个赋值操作调用复制构造函数和重载赋值运算符
- SDL2 渲染复制多个纹理与单个表面
- cout 对象是否保持单个实例,即它永远不会被复制
- 将内容从多个容器复制到单个容器中
- 我可以删除boost::multi_array的单个维度而不复制其内容吗
- 如何从图像矢量复制单个图像到临时cv::Mat
- 我可以同时复制单个shared_ptr吗?
- 在不带指针的C-string中复制单个字符
- 为什么不复制由单个shared_ptr组成的类呢?
- 使用std::copy复制单个字符