只有字符数组的一部分被打印与函数
Only part of char array being printed with function
我尝试编写一个函数来打印字符数组,但由于某种原因,它只将函数的一部分打印到控制台。例如:
#include <iostream>
#include <stdio.h>
using namespace std;
void printString(char s[])
{
int size = sizeof(s) - 1;
for( int i = 0; i < size; i++)
{
cout << *(s + i);
}
}
int main()
{
char fruit[] = "Cherry";
printString(fruit);
}
导致以下输出:
Che
无论我使用哪个单词,都只能打印 3 个字符。任何帮助将不胜感激。
无论我使用哪个单词,都只能打印 3 个字符。任何帮助将不胜感激。
int size = sizeof(s) - 1;
不会做你认为它做的事情。
由于s
在函数调用时衰减为指针,因此sizeof(s)
总是为您提供指针的大小 - 1(在您的情况下似乎是 32 位指针 == 4 字节)。
请改用size_t size = strlen(s);
:
void printString(char s[]) {
size_t size = strlen(s);
for( size_t i = 0; i < size; i++) {
cout << *(s + i);
}
}
您可以执行以下操作:
void printString(char *s)
{
while(*s!=' ')
{
cout << *s;
s++ ;
}
}
或者,您可以将代码编辑为:
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
void printString(char s[])
{
int size = strlen(s);
for( int i = 0; i < size; i++)
{
cout << *(s + i);
}
}
int main()
{
char fruit[] = "Cherry";
printString(fruit);
}
您的问题在以下行中:
int size = sizeof(s) - 1;
由于您正在使用函数来打印字符数组,因此字符数组:
char fruit[] = "Cherry";
衰减为指针,因此sizeof (s)
等效于 sizeof (char*)
,在您的配置中为 4 个字节,因此 size
的值等于 3。
要解决此问题,您需要将数组的大小传递给函数,如下所示。
#include <iostream>
#include <stdio.h>
using namespace std;
void printString(char s[], int size) // Change here
{
for( int i = 0; i < size; i++)
{
cout << *(s + i);
}
}
int main()
{
char fruit[] = "Cherry";
printString(fruit, sizeof(fruit) / sizeof (fruit[0]) - 1); // Change here
}
即便如此,您也需要使用 sizeof(fruit) / sizeof (fruit[0])
这样的结构来返回数组的真实大小,因为sizeof
返回以字节为单位的变量大小,因此虽然它可以与char
一起使用(因为char
的大小是一个字节,但它可能不适用于其他类型的数组(例如 int
数组)。
更新:如果是char
数组,您需要将尝试打印的大小减小 1,因为字符串文字(或一般的类似 C 的字符串 - char 数组)以 NULL 字符结尾(char
值等于 0),这是已知字符串结尾的机制。您实际上不需要打印它。
相关文章:
- 回溯C++不打印函数,因此文件
- 重写打印函数而不是覆盖基类
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 打印传递给打印函数的矢量
- 如何使用重新定义的打印函数打印Lua表?
- 调用和打印函数,在 C++ 中返回数组
- Lua C API 自定义打印函数,在字符串中传递空格时不调用
- C++二叉树打印函数实现
- 如何从主 C++ 向模板类中的方法发送打印函数
- 如果我不打印函数参数的值,则将其转换为等于零
- 打印函数模板的内容进行类指针
- C++打印函数的结果?
- 打印 C++ 函数
- 编写一个通用打印函数来打印数组
- 用于打印函数进入和退出跟踪的宏
- 每当尝试打印函数变量时,C++ cout 错误
- GDB:当没有可用的名称符号时,如何打印函数参数值
- 在lua中重新定义打印函数时出现问题
- 打印函数会返回一个意外值,原因是什么
- IntStack的C++递归打印函数