gpt4 book ai didi

c++ - Powershell 使用 scanf 进行编程的管道

转载 作者:行者123 更新时间:2023-11-30 05:31:58 25 4
gpt4 key购买 nike

最近我从 Windows 的 cmd.exe 转移到了 PowerShell。后来我发现微软决定放弃标准的 stdin 重定向方法 abc.exe < input.txt并建议使用 Get-Content input.txt | .\abc.exe .

不幸的是,新方法使我的应用程序崩溃了。我创建了这个简单的程序来查找问题的根源

#include <cstdio>

int main() {
int x = -1;
scanf("%d", &x);
printf("%d", x);

return 0;
}

发现这个测试程序返回-1而不是input.txt中的数字。

我还测试了像 echo 1 | .\abc.exe 这样的命令和 type input.txt | .\abc.exe并且所有这些都将 -1 打印到标准输出。

如有任何帮助,我将不胜感激。

编辑 1:

$OutputEncoding 命令的结果:

IsSingleByte      : True                                  
BodyName : us-ascii
EncodingName : US-ASCII
HeaderName : us-ascii
WebName : us-ascii
WindowsCodePage : 1252
IsBrowserDisplay : False
IsBrowserSave : False
IsMailNewsDisplay : True
IsMailNewsSave : True
EncoderFallback : System.Text.EncoderReplacementFallback
DecoderFallback : System.Text.DecoderReplacementFallback
IsReadOnly : True
CodePage : 20127

编辑 2:

我创建了这个简单的程序来查看通过管道传输给程序的内容:

#include <cstdio>

int main() {

char l;
while(scanf("%c", &l)) {
printf("%d\n", l);
}

return 0;
}

运行后Get-Content input.txt | .\abc.exe它不断打印对应于 ASCII“换行”字符的 10。

最佳答案

显然,在一切开始正常工作之前,PowerShell 有多个地方需要设置编码。

最后我想出了这个解决方案 - 将此文本下方的行添加到您的 PS 配置文件中:

[Console]::InputEncoding = [System.Text.Encoding]::UTF8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
chcp 1250 // Change here for preferable Windows Code Page. 1250 is Central Europe
$OutputEncoding = [Console]::OutputEncoding
Clear-Host // clear screen because chcp prints text "Active code page: (code page)"

包含这些行后 Get-Content 开始正常运行。

关于c++ - Powershell 使用 scanf 进行编程的管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35338261/

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