将c中不带字符串的char数组复制到另一个数组



将x复制到y,不带头文件string.h

在c++中将char数组复制到另一个不带stry的数组

输入:car a car

我希望输出没有空间或垃圾:caracar

但输出包含垃圾或如果我输入:y[50]={0}输出是一个ward汽车输出

我想输出没有垃圾和" carcar">

#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int i;
char x[50], y[50] ;
cout << "Enter : ";
scanf_s("%[^n]", x, sizeof(x));
for (i = 0; x[i] != ''; i++)
if ((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z'))
y[i] = x[i];
y[i] = '';
cout << y;
}

输出:caracar没有空格或抓取

您的问题是您仅使用单个'索引'变量(i)用于源字符串和目标字符串。但是,只有在实际复制字符时,才应该增加目标索引。目前的情况是,当源字符没有被复制时,您仍然在增加目标索引,因此您跳过缓冲区中的字符,这些字符保留在其原始(即未初始化/垃圾)状态。

你需要一个单独的索引(我们叫它j)为你的目标缓冲区;在for循环开始时将其初始化为零(与i一样),但只有在我们实际复制某些内容时才增加它(这可以最好使用[...]内部的后增量运算符来完成目标:

#include <iostream>
using namespace std;
int main()
{
int i, j; // Need 2 index vars: one for source, one for destination
char x[50], y[50];
cout << "Enter : ";
scanf_s("%[^n]", x, static_cast<int>(sizeof(x))); // Note last argument is "int"
for (i = j = 0; x[i] != ''; i++) // Set "j" to zero at loop start ...
if ((x[i] >= 'a' && x[i] <= 'z') || (x[i] >= 'A' && x[i] <= 'Z')) {
y[j++] = x[i]; // ...but only increment it on copy!
}
y[j] = ''; // Use Last "j" for position of nul terminator
cout << y;
return 0;
}

这是另一个解决方案。比使用原始数组和索引更像c++,但不像使用std::ranges::remove_copy_if:

那么高级。
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::cout << "Enter : ";
std::string x;
std::getline(std::cin, x);
std::string y;
for ((unsigned char const e : x)
if (std::isalpha(e))
y.push_back(e);
std::cout << y << 'n';
}

附加字幕:HolyBlackCat和Adrian Mole。

似乎你的练习是更多的'C',但解决方案看起来像这样,因为你不需要使用(不建议用于生产代码):

int main()
{
const size_t buf_size = 64;
const char* input = "car a car";
char output[buf_size];
const char* input_ptr = &input[0];
const char* output_ptr_end = &output[buf_size - 2]; // leave room for one extra trailing 0
char* output_ptr = &output[0];
while ((*input_ptr != 0) && (output_ptr < output_ptr_end))
{
if (*input_ptr == ' ') input_ptr++; // skip space
*output_ptr++ = *input_ptr++;
}
*output_ptr = 0;
}

在c++中将char数组复制到另一个数组

例如,可以使用std::ranges::copy

没有空间

您可以使用std::ranges::remove_copy_if。例子:

auto is_space = [](char c) {
return c == ' ';
};
std::ranges::remove_copy_if(x, y, is_space);
char input[32];  // obtained text
char output[32];
char*in_pos     =   input;
char*out_pos    =   output;
for(char cur_char; (cur_char=*in_pos++); ) // while NULL not encountered
{
if(
(cur_char>='A'&&cur_char<='Z')|| // uppercase
(cur_char>='a'&&cur_char<='z')|| // lowercase
(cur_char>='0'&&cur_char<='9')   // digits
)
*out_pos++  =   cur_char; // output cur_char
}
*out_pos = 0; // NULL termination

最新更新