【发布时间】:2017-01-25 08:06:42
【问题描述】:
我终于能够在输入和显示 n 个学生详细信息(学生 ID#、姓名和年龄)时生成一个工作代码...虽然名称不是全名,但我想将这些输入写入文本文件,然后也从文本文件中读取。如有任何帮助,我将不胜感激:
#include <stdio.h>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>
using namespace std;
struct student
{
int sno, sage;
char sname[100];
};
int main(int e, char* argv[])
{
struct student s[e];
int i;
ofstream outfile;
outfile.open("info.txt");
printf("How many entries are you making?: ");
scanf("%d",&e);
printf(" \n");
printf("Please enter Student Information:\n");
for(i=0;i<e;++i)
{
s[i].sno=i+1;
printf("\nEnter Information for student %d\n",s[i]);
printf("================================\n");
cout<<"\nEnter (4 digits) student ID No: ";
cin>>s[i].sno;
cout<<"\nEnter student's name: ";
cin>>s[i].sname;
cout<<"\nAge of student: ";
cin>>s[i].sage;
printf("\n");
//If i do this, I get only first set of data
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
/*I am trying to get data into txt file using the loop below but it looks odd and it collects some of the first set of data, and completes it like this: 1212 kop 23
1627953384 1629646589*/
/*for(i=0;i<e;++i)
{
outfile <<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl;
}*/
outfile.close();
}
printf("Displaying information of student(s):\n");
printf("==================================\n");
for(i=0;i<e;++i)
{
printf("\nInformation for Student %d:\n",i+1);
cout<<"\nStudent ID:"<<s[i].sno;
cout<<"\nStudent name: "<<s[i].sname;
cout<<"\nAge of student: "<<s[i].sage;
printf("\n\n");
}
return 0;
}
【问题讨论】:
-
你不应该“跨越溪流”。使用
std::cout或printf。同样,std::cin或fscanf。 -
main函数有两个参数或没有。这两个参数是:1)参数计数和2)参数字符串数组。没有合法的int main(int e)声明。 -
我建议烧掉你正在学习的书或停止访问教程或停止观看视频。这里的问题太多了。
-
您创建了一个输出文件,但不写入。为了更好地参考,请查看文件流部分,尤其是文件输出部分。
-
对不起,Thomas,违反了这条规则……但它有点奏效。我实际上结合了 5 个不同的部分,并提出了一些疯狂的想法来想出这个。文件流的这两行是什么让我的大脑僵住了