首页 > 解决方案 > 如何分隔单词是.txt。文件

问题描述

对不起我的英语不好,但我真的需要帮助解决我的问题。实际上,我不明白如何在这里做附件。我的老师给我们一个任务来编写程序,该程序将写入文件中的每个单词,其中包含我们将从控制台接受的字符。例如,就像我们在控制台中输入“x”一样,r 程序将响应:

x  
\--------------------------------  
xu  
box  
dux  
exl  
fax  
fix  
fox  
kux  
lex  
lux  
mix  
pax  
pix  
sax  
sex  
....  

但我什至不明白如何在这个 .txt 文件中对单词进行排序。我不明白为什么我的程序会写一些奇怪的符号,而且只写了一些时间正确的单词。请帮助编写此代码。您可以从这里下载文件以使用,但只能使用 slobvnik_en:https://elearning.tul。 cz/mod/resource/view.php?id=177071

感谢您的帮助。

int main(int argc, char *argv[])
 {
    FILE *read=NULL;
    int i,j=0;
    char *words[101][101];

    if(read=fopen("slovnik_en.txt","r")==NULL)
    {
        printf("ERROR FILE");
    }

    for(i=0;i<100;i++)
    {
        for(j=0;j<100;j++)
        {
            words[i][j] = 0;
            printf("%c", words[i][j]);
        }
    }
    printf("reading\n");

    for(i=0;i<100;i++)
    {
        for(j=0;j<100;j++)
        {
            fscanf(read,"%c",&words[i][j]);
        }
    }

    for(i=0;i<100;i++)
    {
        for (j = 0; j <100; j++)
        {

            printf("%c",words[i][j]);

        }
    }

    return 0;
}

标签: c

解决方案


注意:为避免“神奇”数字,使用#define语句为这些“神奇”数字赋予有意义的名称。

应用上述内容和对问题的评论给出以下源代码:

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

#define MAX_WORDS 101
#define MAX_WORD_LEN 101


int main( void )
{
    char words[ MAX_WORDS ][ MAX_WORD_LEN ] = {'\0'};

    FILE *fp = fopen( "untitled.c", "r" );
    if( !fp )
    {
        perror( "fopen to read 'slovnix_in.txt' failed" );
        exit( EXIT_FAILURE );
    }

    printf("reading\n");

    for(int i=0; i<100; i++ )
    {
        if( fscanf( fp, "%100s",  words[i] ) != 1 )
        {
            break;
        }
    }

    for( int i=0; i<100; i++ )
    {
        if( words[i] )
        {
            printf( "%s", words[i] );
            puts( "" );
        }

        else
        {
            break;
        }
    }

    return 0;
}

然后针对当前源文件运行它会untitled.c导致:

reading
#include
<stdio.h>
#include
<stdlib.h>
#define
MAX_WORDS
101
#define
MAX_WORD_LEN
101
int
main(
void
)
{
char
words[
MAX_WORDS
][
MAX_WORD_LEN
]
=
{'\0'};
FILE
*fp
=
fopen(
"untitled.c",
"r"
);
if(
!fp
)
{
perror(
"fopen
to
read
'slovnix_in.txt'
failed"
);
exit(
EXIT_FAILURE
);
}
printf("reading\n");
for(int
i=0;
i<MAX_WORDS;
i++
)
{
if(
fscanf(
fp,
"%100s",
words[i]
)
!=
1
)
{
break;
}
}
for(
int
i=0;
i<MAX_WORDS;
i++
)
{
if(
words[i]
)
{
printf(
"%s",
words[i]
);
puts(
""
);
}
else
{
break;
}
}
return
0;
}

推荐阅读