【问题标题】:How can I avoid the garbage?我怎样才能避免垃圾?
【发布时间】:2014-03-15 07:37:28
【问题描述】:
strcpy(home,"");
    for(j=del1;j<del2;j++){
    home[ strlen(home) ] = word[j];

printf("your house is %s",home);

但我得到了垃圾。我尝试这样做:

strcat(word[j],home);

但是当我运行它时它不起作用

我正在尝试制作一个简单的程序来从文件中写入/读取单词:

写:

fp = fopen ( "houses.txt", "a" );
fprintf(fp,"%s&",home);
fclose ( fp );
printf(" Inserted element\n");

阅读:

char c, home[50],word[100];
strcpy(home,"");
int i=0,del1=0,del2=0,j;
FILE *fp;
fp = fopen ( "houses.txt", "r" );
while (c!=EOF)
{
    c=getc(fp);
    word[i]=c;

    i=i+1;
    if (c=='&')
    {
        del2=i-1;
        strcpy(home,"");
        for(j=del1;j<del2;j++)
        {
            strcat(word[i], home);// OR home[ strlen(home) ] = word[j];
        }
        del1=del2;

        printf("%s \n",home);
    }
}
fclose ( fp );

【问题讨论】:

  • 你在做什么?什么是家?和词?
  • 垃圾进,垃圾出。很简单。
  • home 是如何声明的?
  • 所以如果它被覆盖了,那么strlen 将如何找到它? strlen 会找到一些 '\0',可能在数组末尾的位置(除非整个内存中的每个字节都不为零,在这种情况下,您可能会遇到分段错误)。跨度>
  • strcat 期望 char* 作为其第一个参数,但 word[i] 可能是 char。我仍然不知道你在这里真正想要完成什么。

标签: c arrays string file


【解决方案1】:

如果您要做的只是打印文件中的每个&amp; 分隔字符串,那么您应该将字符读入缓冲区,直到找到&amp;。然后,将&amp; 替换为\0,打印缓冲区,然后将插入点重置为缓冲区的开头。像这样(注意没有任何错误检查)。

#include <stdio.h>

int main(int argc, char **argv)
{
    char home[50];
    int i, c;
    FILE *fp;

    fp = fopen ("houses.txt", "r");

    i = 0;

    while ((c = fgetc(fp)) != EOF) {
        if (c == '&') {
            home[i] = '\0';
            puts(home);
            i = 0;
        }
        else {
            home[i++] = c;
        }
    }

    fclose ( fp );

    return 0;
}

或者,您可以使用fscanf 为您寻找&amp;

#include <stdio.h>

int main(int argc, char **argv)
{
    char home[50];
    FILE *fp;

    fp = fopen ("houses.txt", "r");

    while (fscanf(fp, "%[^&]&", home) == 1) {
        puts(home);
    }

    fclose ( fp );

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-24
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多