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
。
不幸的是,新方法使我的应用程序崩溃了。我创建了这个简单的程序来查找问题的根源
#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 到 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
开始正确运行。
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 模板元编程:如何将参数包组合成新的参数包
- Qt Q串行端口未编程设备未关闭
- 模板元编程 - 尝试实现维度分析
- 我是编程新手
- C++编程从外部文本文件定义数组大小
- 了解算法的性能差异(如果以不同的编程语言实现)
- 使用 Gtkmm 以编程方式选择 Gtk::TextView 中的文本
- scanf() 只取数字作为输入,避免使用其他字符
- 如何将可变参数模板转换为多个单个模板?(C++竞争编程调试模板)
- 为什么我的 scanf() 没有在我的数组上迭代我的 for 循环?
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 使用命名空间正确编程
- C++编程:运算符重载中的引用如何工作?
- Arduino 模块化编程与全局和设置
- C++ 运算符修改/元编程策略,用于不那么冗长的语法
- 如何通过 scanf() 读取没有标点符号的字符串?
- 为什么这个scanf()的两个不同的输入会给出两个不同的输出?
- Powershell的管道到使用scanf进行编程