簡體   English   中英

如何在while循環中連接兩個字符串C

[英]how to concatenate two strings in while loop C

我正在使用兩個 txt 文件(“names.txt”、“fixes.txt”),需要逐行讀取這些文件的單詞,並將它們連接到一個新文件(“results.txt”)中。 例如名稱文件包含以下內容:

john
william
brad

並且修復文件包含以下內容:

@123
@321
@qwe

代碼在這里:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[])
{
    char * filename = argv[1];
    char * fixname = argv[2];
    char names[100];
    char fixes[100];
    FILE * fptr = fopen(filename, "r");
    FILE * fpt = fopen(fixname, "r");
    FILE * fp = fopen("results.txt", "w");
    while (fgets ( names, sizeof(names), fptr ) != NULL)
    {
        strtok(names, "\n");
        while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
        {
            fprintf(fp, "%s%s", names, fixes);
        }
    }

    return 0;
}

我想要這樣的結果:

john@123
john@321
john@qwe
william@123
william@321
william@qwe
(and go on)

但是,結果是這樣的:

john@123
john@321
john@qwe

它不會得到其他名稱!

在外部 while 循環的第一次迭代中,內部 while 循環生成輸入文件fixname的 EOF 條件。

所以外部while循環的其他迭代跳過了內部while循環的評估,因為這個條件

while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

等於假。

例如,使用一個外部 while 循環,並在其中使用 if 語句而不是內部 while 循環。

正如 Vlad 所指出的,內循環在外循環的第一次迭代后指向 EOF。 因此,外循環的后續迭代會跳過內循環。

要解決此問題,您可以在每次迭代后將指針“fpt”帶回文件的開頭。

while (fgets ( names, sizeof(names), fptr ) != NULL)
{
    strtok(names, "\n");
    while(fgets ( fixes, sizeof(fixes), fpt ) != NULL)
    {
        fprintf(fp,"%s%s", names, fixes);
    }
    fseek(fpt,0,SEEK_SET);//bring fpt back to the beginning of the stream
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM