【问题标题】:How can i copy certain parts of an array to another in C?如何将数组的某些部分复制到 C 中的另一个部分?
【发布时间】:2015-02-05 05:40:04
【问题描述】:

所以我的程序应该做的是:用这段代码读取一个 .txt 文件。

FILE *fp;
char filename[40],part1[4],part2[4]; 
int c=0,pt1,pt2; 
printf("\nEnter a file name to open: ");
gets(filename); 
if ((fp = fopen(filename, "r"))!= NULL) 
{
    printf("\nThe file %s was opened successfully!",filename);  
}
else
{
    printf("\nThe file didnt open succesfully!");
}

然后像这样将每一行存储在row 字符串中。

fgets(part1,4,fp); 
pt1 = atoi(part1); 
struct input 
{
    char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
};

struct input list[pt1];  

while (c++ < pt1 )  
{
    fgets(list[c].row,30,fp); 
    printf ("\n%s", list[c].row);
}

但问题是,在那之后我必须把行字符串切成小块(对于 exp 的第一行 txt 是 其中每个数字代表什么)所以我想要的是将“1”放入代码[3]字符串中,将“Glass”放入名称[30]字符串等中。我尝试使用isspace()扫描行字符串使其工作,每当它找到一个空格时它就会复制使用 strncpy() 从 0-(空格 - 1)开始的行数组。出于某种原因,当我运行该程序时,它会停止工作。有人可以提出任何建议吗?

【问题讨论】:

    标签: c arrays string


    【解决方案1】:

    所以我想要的是将“1”放入代码[3] 字符串“Glass”中 进入 name[30] 字符串等。

    使用sscanf() 比使用isspace()strncpy() 更容易:

        sscanf(list[c].row, "%2s%19s%2s%2s%2s%2s",
                            list[c].code,
                            list[c].name, list[c].nPieces, list[c].needed, list[c].usage,
                                                                           list[c].nUses)
    

    【讨论】:

      【解决方案2】:

      您似乎想分配一个大小为 pt1 的数组,但这不起作用,因为这是编译时间,并且 pt1 的值是未知的。

      与:

      struct input 
      {
          char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
      };
      

      你声明了一个变量,但似乎你想定义一个类型,所以:

      typedef struct input 
      {
          char name[20],row[30],code[3],nPieces[3],needed[3],usage[3],nUses[3];
      };
      

      然后你必须 malloc 内存:

      struct input list= calloc(pt1, sizeof(struct input));
      

      声明

      struct input list[pt1];
      

      应该给出一个编译器错误(与我的编译器一样)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-01
        • 1970-01-01
        • 2017-04-03
        • 1970-01-01
        相关资源
        最近更新 更多