Username and Password using String

I am a beginner. I already have the code for username and password for a single set. I am trying to figure out how to make it possible to have three different sets of username and password. I have this code, but it only prints "invalid"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <string.h>

int main(){
	
	char userName[3][20] = {"maan", "james1", "taylorswift13"};
	char password[3][20] = {"12345", "67890", "abcde"};
	char user1[20],pass1[30];
	int i;
	
	printf("\nEnter Username:");
	gets(user1);
	printf("\nEnter Password:");
	gets(pass1);
	
	if(strcmp(user1, userName[i])==0 && strcmp(pass1,password[i])==0)
		printf("VALID");
	else
		printf("INVALID");

}


Thank you!
Last edited on
int i; i is uninitialized. i.e. garbage value.

if(strcmp(user1, userName[i])==0 && strcmp(pass1,password[i])==0)
Using uninitialized value of i.

1
2
3
4
if(strcmp(user1, userName[i])==0 && strcmp(pass1,password[i])==0)
printf("VALID");
else
printf("INVALID");

This block of code need to be in a loop in order to compare each of the 3 usernames and passwords.

PLEASE ALWAYS USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.


Thank you for this! Also, sorry about the formatting of my question. It's my first time :) Thanks again!
I already added a loop, but it still prints INVALID everytime.
1
2
3
4
5
6
7
8
for(i=0;i<3;i++){
	
	if(strcmp(user1, userName[i])==0 && strcmp(pass1,password[i])==0)
		printf("VALID");

	else
		printf("INVALID");
}


Hello mariann,

A little rework of your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

//using namespace std;  // <--- Best not to use.

int main()
{
    std::string message;
    char tF = 'n';

    while (tF == 'n')
    {
        std::cout << "\n Please enter message to encode:\n > ";
        std::getline(cin, message);

        //std::cout << " Is this correct? y/n: " << endl << message << endl;
        std::cout << "\n Is this correct? y/n: ";
        std::cin >> tF;

        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
    }

    return 0;
}

for lines 14 and 17 I had to use the "get_s" to get the program to compile. If you can not use this just go back to what you started with.

Andy

Edit: Sorry copied and pasted the wrong code.
Last edited on
Topic archived. No new replies allowed.