fgets()在字符串中包含新行 [英] fgets() includes new line in string

查看:55
本文介绍了fgets()在字符串中包含新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从文档中提取了单词,并将所有单词打印在屏幕上,但是在每个单词打印之后,都有一个空白行.如何避免读取新行或将新行添加到字符串中?

I get the words from my document extracted and all are printed on screen, but after each word printed there is a blank line. How can I avoid reading or adding this new line to the string?

int main(void) {
    FILE *f;
    f = ("words", "r");
    char string[100];
    while (fgets(string, 100, f)) {
         printf("%s", string);
    }
}

此代码不是复制粘贴的,因此我本可以忘记一些小片段,但应该可以工作.在words.txt中,我每行有一个单词.我的程序将它们全部打印到屏幕上,但是在每个单词之后添加新行.我不希望它添加新行或空格.因此,如果txt的一行上有 Hello ,而下一行是 Bye ,则我希望它打印 HelloBye .最终程序的目的不是打印字符串,而是将字符串用于其他用途,因此我确实需要一个字符串,该字符串的末尾或换行符必须是不带空格的文本.

This code was not copy pasted, so I could have forgotten tiny pieces but should work. In words.txt I have one word on each line. My program prints them all to screen, but adds a new line after each word. I do not want it to add a new line, or a space. So if the txt had Hello on one line and Bye on the next line, I want it to print HelloBye. The objective of the final program will not be to print the string, it will be to use the string for something else, so I do need a string that only has the text without spaces at the end or new lines.

推荐答案

尝试一下.

int main()
{
    FILE *f;
    f = ("words", "r");
    char string[100];
    while (fgets(string, 100, f))
    {
        char * message = strtok(string, "\n");
        printf("%s", message);
    }
}

strtok 将字符串标记为您的消息 \ n . fgets 将捕获 \ n 令牌

strtok tokenizes the string into your message, \n. fgets will capture the \n token

这篇关于fgets()在字符串中包含新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆