2016-10-20 2 views
-3

Я студент, все еще изучающий C++, и я просто начинающий. Вот мой код. Проблема в том, что последнее имя пользователя и пароль дважды сохраняются в текстовом файле. Хотя я использовал систему для открытия других моих программ, потому что я я просто начинающий, и это был самый простой способ, которым я мог бы понять. Спасибо заранее за помощь.Почему данные вводятся дважды?

// Projectregus.cpp : Defines the entry point for the console application. 


#include "stdafx.h" 
#include<iostream> 
#include<fstream> 
#include<time.h> 
#include<cstdlib> 
#include<conio.h> 
using namespace std; 
ifstream users; 
class usersdet 
{ 
    public: 
char username[100]; 
char password[100]; 
double score; 
void assignpass(char pass[]) 
{ 
    int k; 
    for (int j = 0; pass[j] != '\0'; ++j) 
    { 
     password[j] = pass[j]; 
      k = j; 
    }; 
    password[k+1] = '\0'; 
} 
}A,B,C; 
    class quiz 
{ 
    public: 
char question[10000]; 
char option1[1000]; 
char option2[1000]; 
char option3[1000]; 
char option4[1000]; 
char answer; 
}; 
/* ***************************************Function login() defination begins here**************************************** */ 
void login() 
    { 
    cout << "Sign In to continue....\nEnter your username:"; 
    cin >> B.username; 
    int flag = 0, choice; 
    users.open("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\userdat.txt", ios::in|ios::binary); 
if (!users.is_open()) 
{ 
    cout << "fatal error!"; 
    exit(0); 
} 
while (!users.eof()) 
{ 
    users.read((char *)&A, sizeof(A)); 
    if (strcmp(A.username, B.username) == 0) 
    { 
     flag = 1; 
     break; 
    } 
    else flag = 0; 
}; 
if (flag == 0) 
{ 
    cout << "Account not found!"; 
    cout << "\nMENU:\n1.Want to make new account?\t2.Retry?"; 
    cin >> choice; 
    switch (choice) 
    { 
    case 1:system("start E:\\Users\\Utkarsh\\Documents\\Projectnewus.exe"); 
     exit(0); 
     break; 
    case 2:system("start E:\\Users\\Utkarsh\\Documents\\projectregus.exe"); 
     exit(0); 
     break; 
    default: cout << "Wrong input!"; 
     exit(0); 
    } 
} 
cout << "Enter password:"; 
char pass[100]; 
int i = 0; 
char a; 
for (i = 0;;) 
{ 
    a = _getch(); 
    if ((a>='a' && a<='z') || (a>='A'&&a <='Z') || (a>='0'&& a<='9')) 
    { 
     pass[i] = a; 
     ++i; 
     cout << "*"; 
    } 
    if (a =='\b' && i>= 1) 
    { 
     cout << "\b \b";//rub the character behind the cursor. 
     --i; 
    } 
    if (a == '\r')//if enter is pressed 
    { 
     pass[i] = '\0'; 
     break; 
    } 
} 
cout << endl; 
B.assignpass(pass); 
if (strcmp(A.password, B.password) == 0) 
{ 
    cout << "Login successful!"; 
    cin.ignore(); 
    getchar(); 
} 
else 
{ 
    cout << "Login failure !"; 
    cin.ignore(); 
    getchar(); 
    exit(0); 
    } 
    users.close(); 
} 
    /* *********************************QUIZGAME function defination  here**************************************************** */ 
    void quizgame() 
    { 
    B.score = 0; 
    cout << "\nLets begin the QUIZ " << A.username; 
    cout << "\n Your last score was:" << A.score; 
    getchar(); 
    ifstream game; 
    cout << "Which quiz do you want to play?\n1.General Knowledge\n2.General Science\n"; 
    int choice2; 
    cin >> choice2; 
    cin.ignore(); 
    switch (choice2)   //choice of file to be opened 
    { 
case 1:game.open("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\quizGK.txt", ios::in | ios::binary); 
    if (!game.is_open()) 
    { 
     cout << "fatal error!"; 
     exit(0); 
    } 
    break; 
case 2:game.open("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\quizGS.txt", ios::in | ios::binary); 
    if (!game.is_open()) 
    { 
     cout << "fatal error!"; 
     exit(0); 
    } 
    break; 
default:cout << "Wrong input!!"; 
    exit(0); 
}; 
quiz X; 
int qno, seedval, count, verification[50], verificationflag = 1, iotemp = 0, ioflag = 0, gamecounter = 0; 
for (int in = 0; in < 6; ++in)   //initialises verification[] 
    verification[in] = 0; 
char choice1 = 'y'; 
time_t t; 
seedval = (unsigned)time(&t); 
srand(seedval); 
while (choice1 == 'y'&& gamecounter != 6) 
{ 
    while (verificationflag == 1)   //Assures unique question 
    { 
     qno = (rand() % 6) + 1; 

     for (int io = 0; io < 6; ++io) 
     { 
      if (verification[io] == qno) 
      { 
       ioflag = 1; 
      } 
     } 

     if (ioflag == 0) 
     { 
      verification[iotemp] = qno; 
      verificationflag = 0; 
      ++iotemp; 
     } 
     ioflag = 0; 

    } 

    game.seekg(0); 
    for (count = 0; count < qno; ++count) 
    { 
     game.read((char *)&X, sizeof(X)); 
    } 
    system("cls"); 
    cout << "Your " << gamecounter + 1 << " Question\n\n"; 
    cout << X.question << endl << X.option1 << endl << X.option2 << endl << X.option3 << endl << X.option4 << endl << "Enter answer:"; 
    char answer; 
    int score = 0; 
    cin >> answer; 
    cin.ignore(); 
    if ((answer == X.answer) || (answer == tolower(X.answer))) 
    { 
     cout << "correct answer"; 
     ++B.score; 
    } 
    else 
    { 
     cout << "Wrong answer/nCorrect answer is "<<X.answer; 

    } 
    cout << "\nYour current score:" << B.score; 
    cout << "\nWant to play more?(y/n)"; 
    cin >> choice1; 
    verificationflag = 1; 
    ++gamecounter; 
    if (gamecounter == 6) 
     cout << "GAME ENDED!"; 

    } 
    game.close(); 
} 
    /* ********************************************MAIN BEGINS  HERE******************************************************** */ 
void main() 
{ 
system("cls"); 
login(); 
system("cls"); 
quizgame(); 
users.open("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\userdat.txt", ios::in|ios::binary); 
ofstream temp; 
temp.open("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\temp.txt",ios::out|ios::binary); 
if (!temp.is_open()) 
{ 
    cout << "fatal error!"; 
    exit(0); 
} 
if (!users.is_open()) 
{ 
    cout << "fatal error!"; 
    exit(0); 
} 
users.seekg(0); 
while (!users.fail()) 
{ 
    users.read((char*)&C, sizeof(C)); 
    if (strcmp(C.username, A.username) != 0) 
     temp.write((char*)&C, sizeof(C)); 
} 
A.score = B.score; 
temp.write((char*)&A, sizeof(A)); 
users.close(); 
temp.close(); 
cout << A.username << endl << A.password << endl << A.score; 
remove("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\userdat.txt"); 
rename("E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\temp.txt", "E:\\Users\\Utkarsh\\Documents\\Visual Studio 2015\\Projects\\Project\\Debug\\userdat.txt"); 
system("pause"); 


} 






what i am getting in my text file is: 
muskaan ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌmuskaan23 ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ  sample ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌsample23 ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ  sample ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌsample23 ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ  utkarsh ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌutkarsh23 ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ  ð? 
    Here muskaan,utkarsh and sample is username i entered using another program 
+0

Просьба представить минимальный, полный, проверяемый пример: http://stackoverflow.com/help/mcve. И лучшее кодирование кода всегда приветствуется. –

ответ

2

Вы ожидаете функцию eof, чтобы предсказать будущее и сказать, будет ли будущее чтение успеха или неудачи. К сожалению, эта функция только сообщает о прошлом.

Скажите, что у вас есть список «яблоко», «апельсин», «груша». Вы читаете «яблоко» и обрабатываете его. Вы читаете «оранжевый» и обрабатываете его. Вы читаете «грушу» и обрабатываете ее. Затем вы попытаетесь прочитать снова и проиграть. Но вы не проверяете, удалось ли прочитать, так что вы снова обрабатываете «грушу». Затем вы выходите из цикла, потому что вы попадаете в конец файла.

Забудьте проверить eof. Это не полезно. Вместо этого выходите из цикла, когда сбой чтения. И, конечно, если сбой чтения, не обрабатывает устаревшие данные в вашем буфере, которые вы уже обработали в предыдущем чтении.