【问题标题】:Powershell's pipe to program using scanfPowershell 使用 scanf 进行编程的管道
【发布时间】:2016-02-11 11:35:56
【问题描述】:

最近我从 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;
}

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

我还测试了 echo 1 | .\abc.exetype 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 中显示 $OutputEncoding 的值。还重写本机应用程序以逐个字符读取字符并打印读取代码,以便知道究竟是什么管道传递给它。
  • 您的 Edit 2 程序不会在 EOF 上停止并继续打印最后一个字符。应该是while(scanf("%c", &amp;l)!=EOF)。我还编译了你的第一个测试程序,它对我来说很好。我输入:echo 12345 | .\test.exe,它打印出12345
  • 最近我一直在使用 PowerShell,以便让 Python 在控制台中正确显示 Unicode 字符(例如:print "ąę" 导致控制台中的 ae)。在执行此操作时,我找到了将这些行 [Console]::InputEncoding = [System.Text.Encoding]::UTF8[Console]::OutputEncoding = [System.Text.Encoding]::UTF8 添加到 PS 配置文件配置的解决方案。结果,scanf 收到了额外的字节。

标签: c++ windows powershell pipe scanf


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多