Powershell的管道到使用scanf进行编程

Powershell's pipe to program using scanf

本文关键字:scanf 编程 管道 Powershell      更新时间:2023-10-16

最近我从Windows的cmd.exe转移到PowerShell。后来我发现Microsoft决定放弃标准的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.exetype input.txt | .abc.exe 这样的命令,它们都打印 -1 到 stdout。

我将不胜感激任何帮助。

编辑 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("%dn", 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开始正确运行。