-1

I want to request the a username and password from 6 users, and then save this username and password into a text file on my desktop. I built a structure that has one variable to store the password and a char array with a length of 25.

struct users {
    int password;
    char username[25];
}

When I want to request the username in the main() function, I use the cin.get() function.

cin.get(username,25);

The program stops after the second cin function when it is storing the password. Why is that?

#include <iostream>
#include <fstream> 

struct users {
    char username[25];
    int password;
} user[6]; 

using namespace std;
int main() {  
    cout << "Sign up x6" << endl;
    for(int i=0;i<6;i++){
        cout << "Username:";
        cin.get(user[i].username,20);
        cout << "Password:";
        cin >> user[i].password;
    }
    std::ofstream file;
    file.open("C:/Users/Programmer/Desktop/sa.txt",ios::app);
    for(int i=0;i<6;i++){
        file << "first user\n" << user[i].username << endl << user[i].password << endl;
        cout << "\n \n \n";
    }
}
Sean Dawson
  • 5,587
  • 2
  • 27
  • 34

2 Answers2

-1

i found solution that using "gets" function .. which inside stdio.h library:
function "gets" will request the user of value then store the value of variable. (username)
char username[25];
gets(username[25]);

but this function "gets" get only value of "char" type variables so i changed "password" variable type to char char password[25];
gets(password[25]);

    #include<iostream>
    #include <fstream> 
    #include<stdio.h>
struct users
{
char username[25];
char password[25];
} user[6];
using namespace std;
int main()
{
cout << "Sign up x6" << endl;
for (int i = 0; i < 6; i++)
{
    cout << "username:";
    gets(user[i].username);
    cout << "Password:";
    gets(user[i].password);
}
std::ofstream file;
file.open("C:/Users/Programmer/Desktop/sa.txt", ios::app);
for (int i = 0; i < 6; i++)
{
    file <<"("<<i<<") user\n" << user[i].username << endl <<  user[i].password<< endl;          
    cout << "\n \n \n";
}
}
-2

use std::cin.getline(user[i].username,20) instead.

andress hoyo
  • 161
  • 1
  • 14
  • Suffers almost exactly the same problem as the asker's code. The '\n' most likely left in the stream after `cin >> user[i].password;` breaks the parser. – user4581301 Nov 23 '17 at 01:31
  • after i did that ,, the cin.getline function run only once inside "for loop" so asked me of password 6 times (true) but asked me of username only once time! (false) – Yasser A. ElShbrawy Nov 25 '17 at 00:45