我有一个简单的 C++ 程序,它使用 scanf
读取 stdin
并使用 printf
将结果返回到 stdout
:
#include <iostream>
using namespace std;
int main()
{
int n, x;
int f=0, s=0, t=0;
scanf("%d",&n); scanf("%d",&x);
for(int index=0; index<n; index++)
{
scanf("%d",&f);
scanf("%d",&s);
scanf("%d",&t);
if(x < f)
{
printf("first\n");
}
else if(x<s)
{
printf("second\n");
}
else if(x<t)
{
printf("third\n");
}
else
{
printf("empty\n");
}
}
return 0;
}
我正在用 g++ 编译并在 linux 下运行。我使用文本文件作为输入来执行程序,并将输出通过管道传输到另一个文本文件,如下所示:
program < in.txt > out.txt
问题是 out.txt 看起来像这样:
result1_
result2_
result3_
...
其中“_”是每行末尾的额外空格。我正在 gedit 中查看 out.txt。
如何在没有额外空间的情况下生成输出?
我的输入文件是这样的:
2 123
123 123 123
123 234 212
编辑:我能够找到解决此问题的方法:printf("\rfoo");
感谢您的意见!
最佳答案
尝试从 printf()
语句中删除“\n”,然后再次运行代码。如果输出文件看起来像一个长单词(没有空格),那么您就知道在文本后插入的唯一内容是“\n”。
我假设您用来读取 out.txt 文件的编辑器只是让它看起来输出后有一个额外的空格。
如果还不能确定,可以写一个快速程序,读入out.txt,确定每个字符的ASCII码。
关于c++ - printf ("something\n") 输出 "something "(附加空间) (g++/linux/用gedit读取输出文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/350922/