C语言 如何调整行和列?



我写了这段代码,我希望它是 1 行和 2 列。我使用了 2d 数组,但当我运行代码时,它不允许输入姓名和出生日期。那么如果不接受输入,它将如何出现在文本文件中?

预期产出

Name     Date of Birth
John     0221999

这是代码

int main(char *name, size_t namesize, char *dob, size_t dobsize){
char listing[1][2] = {"Name ","Date of birth "};
char *another_list[1][2];
int i, j;
FILE * fp;
fp = fopen("/home/bilal/Documents/file.txt","w+"); 

for (i=0; i<1; i++){
for(j=0; j<2; j++){
printf("Enter your %s: ",listing[i][j]);
fgets(another_list[i][j], sizeof(another_list[i][j]), stdin);
for (i=0; i<1; i++){
for (j=0; j<2; j++){
fputs(listing[i][j], fp);
}
}
}
}
fclose(fp);
return 0;
}
int main(char *name, size_t namesize, char *dob, size_t dobsize) 

main的有效签名包括:

int main(void)

int main(int argc, char *argv[]) 

尺寸错误:

char listing[1][2] = {"Name ","Date of birth "};

让编译器为您计数,第一个维度不是必需的:

char listing[][15] = {"Name ","Date of birth "};

由于这些是不可修改的标题:

const char *listing[] = {"Name ","Date of birth "};

所有这些循环都是一团糟,两个循环就足够了。

您的代码工作:

#include <stdio.h>
int main(void)
{
const char *listing[] = {"Name", "Date of birth"};
char data[2][51];
int done = 0;
FILE *fp;
fp = fopen("/home/bilal/Documents/file.txt", "w+");
puts("Press CTRL+D to exit");
while (!done)
{
for (int i = 0; i < 2; i++)
{
printf("Enter your %s: ", listing[i]);
// Scan until n with buffer protection
if (scanf(" %50[^n]", data[i]) != 1)
{
done = 1;
break;
}
}
if (!done)
{
fprintf(fp, "%s %sn", data[0], data[1]);
}
}
fclose(fp);
return 0;
}

最新更新