简体   繁体   English

如何在C字符串中编写和读取多个单词

[英]How to write and read more than one word in C string

I'm doing program and in this program i have two processes, server and client. 我正在做程序,在这个程序中我有两个进程,服务器和客户端。 Server have to read string from input and then write into FIFO file. 服务器必须从输入读取字符串,然后将其写入FIFO文件。 Client have to read strings from FIFO file and then wrote into .txt file. 客户端必须从FIFO文件中读取字符串,然后将其写入.txt文件。 This are only function responsible for server and client. 该功能仅负责服务器和客户端。 File FIFO and fork'ing is doing in main function. 文件FIFO和分叉正在执行主要功能。

void server(void)
{
    FILE *fp1, *fp2;
    char string[100];

    while(1)
    {
        fp1 = fopen("FIFO1", "w");
        fprintf(stdout, "Type string: ");
        scanf("%s", string);
        fputs(string, fp1);
        fclose(fp1);

        sleep(1);
    }
}
void client(void)
{
    FILE *fp,*fp1;
    char string[100];
    while(1)
    {
        fp = fopen("FIFO1", "r");
        fgets(string, 100, fp);
        fclose(fp);
        fp1 = fopen("file.txt", "a");
        fprintf(fp1,"%d_file: I get: %s\n", getpid(), string);
        fclose(fp1);    
    }
}

And my problem is when i type a string like "stack overflow", when i have two word, in my file.txt i get to lines: 我的问题是,当我在“ file.txt ”中输入两个词时,当我输入“ stack stackover”之类的字符串时,我会进入以下行:

8965_file: I get: stack
8965_file: I get: overflow

Is there any way to write this in one line ? 有什么办法可以一行编写吗? Like this: 像这样:

8965_file: I get: stack overflow

It's because of scanf() which stops reading when a white space occurs for the "%s" specifier, change it to "%99[^\\n]" or use fgets() instead but keep in mind that fgets() will read the '\\n' and fputs() will add one so you might end up with more lines than you want. 这是因为scanf()会在"%s"说明符出现空白时停止读取,将其更改为"%99[^\\n]"或改用fgets()但要记住fgets()会读取'\\n'fputs()会加一,所以您最终可能得到比您想要的更多的行。

Hint : For an array use fgets(string, sizeof(string), fp); 提示 :对于数组,请使用fgets(string, sizeof(string), fp); to make your code easier to maintain. 使您的代码更易于维护。

You can use gets(string) to get more than one word instead of using scanf() . 您可以使用gets(string)来获取多个单词,而不是使用scanf()

Reference Link : www.keizerkong.com/c/c_string.html 参考链接: www.keizerkong.com/c/c_string.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM