gpt4 book ai didi

两个系统上同一程序的 C++ 不同输出

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:57 25 4
gpt4 key购买 nike

所以我目前正在做一项作业,在我的笔记本电脑上它工作正常但在我的 PC 上输出是乱码。

Enter a command:
a
Enter a command:
a´Zéÿ command received.

忽略我乱七八糟的输出为什么输出中有'Zéÿ?
在我的笔记本电脑上,代码按预期工作。

这是一个小示例代码:

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <iostream>
using namespace std;

int main(){
int pipefd[2];
pid_t cpid, ppid;
char buf[100];

if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}

cpid = fork();

if (cpid == 0) {
read(pipefd[0], &buf, 1);
cout << buf << " command received." << endl;
}
else {
cout << "Enter a command: " << endl;
cin >> buf;
cout << "buf: " << buf << endl;
size_t len = strlen(buf);
write(pipefd[1], &buf, len);
}

return 0;
}

输出略有不同,只是
收到一个`命令。而不是
收到命令。

E: 我在我的电脑上使用 antergos,在我的笔记本电脑上使用 elementary,在这两个系统上,终端都是 urxvt

最佳答案

您必须初始化缓冲区,否则它将包含该位置之前内存中的所有内容,这就是正在打印的内容。

关于两个系统上同一程序的 C++ 不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43551897/

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