我遇到了一个关于使用函数strchr的问题,我的代码是
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
char linebuf[1000];
int main()
{
char linebuf[] = "sortie.bin:8276 bytes";
char *colonPos = strchr(linebuf,':'); // strchr returns the pointer of ":"
cout<<colonPos<<endl; // display: ":8276 bytes"
cout<<*colonPos<<endl; // display: ":"
cout<<linebuf<<endl; // display: "sortie.bin:8276 bytes"
*colonPos = 0;
cout<<linebuf<<endl; // display :"sortie.bin"
return 0;}
我的问题是为什么:当我放入*colonPos = 0时,linebuf改变了,":“之后的所有东西都被取消了,但实际上我没有改变linebuf的任何东西。
发布于 2017-03-13 22:46:47
colonPos是指向linebuf中的:字符的指针。当您用\0替换:时,您是在“截断”字符串,因为C字符串是"null终止的“,这意味着按照惯例,它们会在第一个零字节停止。
如果将C字符串的第N个字符设置为\0 (零字节),则该字符串的长度最多为N个字符。这就是C字符串的定义方式。
发布于 2017-03-13 22:46:56
在执行*colonPos = 0时,需要修改数组以使其看起来像"sortie.bin\08276 bytes"。也就是说,您将冒号替换为字符串终止符,该替换是对linebuf的修改(或更改)。
发布于 2017-03-13 23:04:20
为char *类型的流和对象重载的运算符operator << (极少数例外的表达式中使用的字符数组转换为指向其第一个元素的指针)输出字符,直到遇到零字符。也就是说,运算符将字符数组视为包含C字符串。
如果你想输出整个数组,你应该使用write方法。例如
#include <iostream>
#include <string>
#include <cstring>
int main()
{
char linebuf[] = "sortie.bin:8276 bytes";
size_t n = strlen( linebuf );
char *colonPos = std::strchr( linebuf,':' );
*colonPos = 0;
std::cout.write( linebuf, n ) << std::endl;
return 0;
}程序输出为
sortie.bin8276 byteshttps://stackoverflow.com/questions/42766460
复制相似问题