繁体   English   中英

Powershell使用scanf进行编程的管道

[英]Powershell's pipe to program using scanf

最近,我从Windows的cmd.exe移到了PowerShell。 后来我发现Microsoft决定放弃标准的stdin重定向方法abc.exe < input.txt并建议使用Get-Content input.txt | .\\abc.exe 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 echo 1 | .\\abc.exetype input.txt | .\\abc.exe type 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("%d\n", l);
    }

    return 0;
}

运行Get-Content input.txt | .\\abc.exe Get-Content input.txt | .\\abc.exe它会继续打印10,它对应于ASCII“换行”字符。

显然,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开始正确运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM