2016-09-17 2 views
0

Я смог наконец создать рабочий код при вводе и отображении n сведений о студенте (ID студента, имя и возраст) ... хотя имя не является полным именем, Я хотел бы записать эти данные в текстовый файл, а затем прочитать из текстового файла. Я буду признателен за любую помощь, пожалуйста:Запись ввода в файл и чтение из файла в C++

#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; 

} 
+0

Вы не должны «пересекать потоки». Используйте либо 'std :: cout', либо' printf'. Аналогично, 'std :: cin' или' fscanf'. –

+0

Функция 'main' имеет два параметра или ни один. Два параметра: 1) количество параметров и 2) массив строк параметров. Не существует юридической декларации 'int main (int e)'. –

+0

Я рекомендую записать книгу, которую вы изучаете, или прекратить посещение тургора или прекратить просмотр видео. Слишком много проблем. –

ответ

0

Я предлагаю начать с простой программой, которая записывает в файл:

#include <fstream> 
#include <iostream> 
#include <cstdlib> 

int main(void) 
{ 
    std::ofstream output_file("text.txt"); 
    std::cout << "Writing to output file.\n"; 
    output_file << "This is my text.\n"; 
    output_file.flush(); 
    std::cout << "Finished writing to file.\n"; 
    output_file.close(); 

    std::cout << "Paused. Press Enter to continue.\n"; 
    std::cin.ignore(100000, '\n'); 
    return EXIT_SUCCESS; 
} 

После выполнения вышеуказанной программы, вы должны убедиться, что текстовый файл содержит правильный текст.

Далее вы можете добавить другой код, например, запросить пользователя и получить его.

0

Я думаю, вы не знаете, как читать или писать через файл. Вот почему у вас проблемы. Есть два способа, которыми люди обычно пользуются. Пройдите эти два примера учебника для хорошего понимания этих методов. - c methods - c++ methods

Это код, который я изменил читать и писать файлы, используя оба метода -

Given Input file - student.txt. //first line No. of input 
2 
1234 manish  34 
4321 mukesh  43 

Code 
#include <iostream> 
#include <cstdio> 
#include <fstream> 

using namespace std; 

struct student 
{ 
int sno, sage; 
char sname[50]; 
}; 

//Read data using C Method 
void ReadAndWriteCMethod(){ 
    student s[100]; 


    FILE* f; 
    f = fopen("student.txt","r"); 
    int N; 
    fscanf(f,"%d",&N); 

    **//Reading from file** 
    for(int i=0; i<N; i++){ 
     fscanf(f,"%d %s %d",&s[i].sno, &s[i].sname, &s[i].sage); 
    } 
    fclose(f); 

    **//Writing over file** 
    f = fopen("wstudent1.txt","w+"); 
    for(int i=0; i<N; i++){ 
     cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl; 
     fprintf(f,"%d %s %d\n",s[i].sno,s[i].sname,s[i].sage); 
    } 
    fclose(f); 
} 

//Reading and writing using C++ 
void ReadAndWriteCPlusPlusMethod(){ 
    student s[100]; 

    **// Reading data** 
    std::ifstream fin("student.txt"); 

    char s2[100]; 
    int N; fin>>N; 
    for(int i=0; i<N; i++){ 
    fin>>s[i].sno>>s[i].sname>>s[i].sage; 
    cout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl; 
    } 
    fin.close(); 

    **//Writing data** 
    std::ofstream fout("wstudent2.txt"); 
    for(int i=0; i<N; i++){ 
    fout<<s[i].sno<<" "<<s[i].sname<<" "<<s[i].sage<<endl; 
    }  
    fout.close(); 
} 

int main() 
{ 
    ReadAndWriteCMethod(); 
    ReadAndWriteCPlusPlusMethod(); 
} 

После запуска, это создаст два файла wstudent1.txt и wstudent2. txt.

+0

Мышление в C++, я все еще не могу заставить работать мой код. Думаю, я собираюсь бороться немного больше. Я думаю, что просто хочу записать данные в текстовый файл ... Я больше не хочу читать данные. – McNeal

Смежные вопросы