C语言 C puts() 没有换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17238784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:45:00  来源:igfitidea点击:

C puts() without newline

cfilenewlineputs

提问by Constantine

I currently have this program that prints a text file on the console, but every line has an extra new line below it. if the text was

我目前有这个程序可以在控制台上打印一个文本文件,但每一行下面都有一个额外的新行。如果文本是

hello world

你好,世界

it would output hello

它会输出你好

world

世界

the code is this

代码是这样的

#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;
}

采纳答案by dasblinkenlight

puts()adds the newline character by the library specification. You can use printfinstead, where you can control what gets printed with a format string:

puts()按库规范添加换行符。您可以printf改为使用,您可以在其中控制使用格式字符串打印的内容:

printf("%s", input);

回答by Alex North-Keys

Typically one would use fputs() instead of puts() to omit the newline. In your code, the

通常会使用 fputs() 而不是 puts() 来省略换行符。在您的代码中,

puts(input);

would become:

会成为:

fputs(input, stdout);

回答by Ferrarezi

You can also write a custom putsfunction:

您还可以编写自定义puts函数:

#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;
}

Output:

输出:

testing C puts() without newline