Con*_*ine 25 c newline file puts
我目前有这个程序在控制台上打印一个文本文件,但每行下面都有一个额外的新行.如果文本是
你好,世界
它会输出你好
世界
代码是这样的
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
FILE* fp;
char input[80], ch = 'a';
char key[] = "exit\n";
int q;
fp = fopen("c:\\users\\kostas\\desktop\\original.txt", "r+");
while (!feof(fp)) {
fgets(input, 80, fp);
puts(input);
}
fclose(fp);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*eys 48
Typically one would use fputs() instead of puts() to omit the newline. In your code, the
puts(input);
Run Code Online (Sandbox Code Playgroud)
would become:
fputs(input, stdout);
Run Code Online (Sandbox Code Playgroud)
puts()
按库规范添加换行符.您可以使用printf
,在那里您可以控制使用格式字符串打印的内容:
printf("%s", input);
Run Code Online (Sandbox Code Playgroud)
您还可以编写自定义的put函数:
#include <stdio.h>
int my_puts(char const s[static 1]) {
for (size_t i = 0; s[i]; ++i)
if (putchar(s[i]) == EOF) return EOF;
return 0;
}
int main() {
my_puts("testing ");
my_puts("C puts() without ");
my_puts("newline");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
testing C puts() without newline
Run Code Online (Sandbox Code Playgroud)