[英]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.exe
並type 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.