gpt4 book ai didi

c++ - 基本的 string.h 问题(C++)

转载 作者:行者123 更新时间:2023-11-28 01:06:18 25 4
gpt4 key购买 nike

我有一个简单的 C++ 文件,它从文本文件中删除字符,尽管我想更改它。

文本字符串如下:

XXXXX|YYYYYYYYYYYYYYYYYYY

目前它删除

|YYYYYYYYYYYYYYYYYYY

从字符串中,虽然我想删除它:

XXXXX|

相反,所以实际上取出左侧而不是右侧。

我现在的代码是:

#include <stdio.h>
#include <string.h>

main(int argc, char *argv[])
{
char s[2048], *pos=0;
while (fgets(s, 2048, stdin))
{
if (pos = strpbrk(s, "|\r\n"))
*pos='\0';
puts(s);
}
return 0;
}

最佳答案

你应该很少使用 <string.h>在 C++ 程序中。

您可能应该使用 <string> ;你也许可以使用 <cstring> .

这甚至没有查看您的代码 - 只需忘记 <string.h>如果您正在编写 C++,则存在;它是 C 功能的 C 头文件。类似的评论适用于 <stdio.h> ;它是一个 C 头文件,应该很少在 C++ 中使用(通常使用 <iostream>,或偶尔使用 <cstdio>)。

你的 main()函数需要返回类型 int (在 C++ 和 C99 中)。由于您需要管道后的信息,因此您可以编写(完全有效的 C(C89、C99)程序——根本不使用 C++ 的任何独特功能,尽管 C++ 编译器也会接受它):

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[])
{
char s[2048];
while (fgets(s, sizeof(s), stdin))
{
char *pos = strpbrk(s, "|\r\n");
if (pos != 0)
fputs(pos+1, stdout);
}
return 0;
}

使用 fputs()而不是 puts()以避免双倍行距输出。

关于c++ - 基本的 string.h 问题(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5921850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com