Compare Two pointer Arrays One of them from .h and one of them from cin - c++

I am newbie.
I have got a school project that there is a header file and it has got 82 usernames. Like
char *usernames[] ={a1,a2,a3,.... a82};
char *passwords[] =[p1,p2,...p82);
And I have finished large amount of my project but still I couldn't write an usefull code for login stage.
My code has to do take username and then asking for password.
For this stage I think basicly that loop:
char *usernamecheck;
char *passwordcheck;
cout<<"Please login. \n Username\n ";
cin >> usernamecheck ;
for(int flag=0;flag<82;flag++)
{
if(usernamecheck==usernames[a]){
passwordcheck==password[a];
}
else {
}
}
cout<<"Please enter your password\n";
....
Then I will compare password taken from user and from header file.
I want to ask that point we didn't see that point on course. I have no idea how can I compare 2 char pointers. I tried to use as string but I have failed.

This:
char *usernamecheck;
...
cin >> usernamecheck ;
is going to be undefined behaviour. There is no memory associated with usernamecheck. You say:
I tried to use as string but i have failed.
So dont use old archaic, methods when there are shiny new c++ ones available:
std::string usernamecheck;
...
cin >> usernamecheck;
bool isUser = usernamecheck == username;
Done.
use std::string, its the bomb.
Live example.

Related

How do I get a variable amount of input from cin?

I've been working on a calculator and I am very close to getting it working, but I need to find a way to have the amount of numbers and operators that the user puts in to be up to the user. This is a simpler test version of what I have so far that I need to apply this to. I left out a few things but this is the exact part of the code I need to apply it to. The user should be able to input any amount of numbers and operands as long as it is under 20 of each. I don't want to stick to a rigid form of input, like cin >> numIn[n]; cin >> operator1[n], because then you would HAVE to end with an operator, for example.
#include <iostream>
float numIn[20];
char operator1[20];
int main(){
int n = 0;
while (n < 20){
std::cin >> numIn[n] >> operator1[n];
switch (operator1[n]){
case '+':
std::cout << numIn[n] + numIn[n];
break;
default:
std::cout << "does not work";
}
}
}
I edited this question to be more focused and clear. I added the part of the text above about how I need to have a 'fluid' way of input. If this doesn't make it more clear I don't know what does.
Use getline to get a whole line of input from the user.
Then use that string to construct a stringstream, which you can use your >> on to extract the numbers and single-char operators. But now you get an error when you try to read past the end of the original string. It knows you are done, because it has the complete input committed before it started to read, unlike an always-open terminal where the user could always type more.
use std::cin >> numIn[n] and std::cin >> operator1 [n]
as #Ivan suggested in the replies

Storing Arrays of Structs in external files in C++

So I'm working on a homework assignment for my CS162 class which requires me to make a program that allows the user to input their class plan for college. The user inputs classes they have taken, are currently taken, and/or plan on taking, with the categories of: department/class number, class name, term/year, whether or not the class is required for their major, and any additional comments. Then, the program is supposed to store this invermation with external data files so that the classes are stored and won't be lost. The program should be able to store up to 60 classes in memory.
I know how to create arrays of strucs and I know the basics behind external files, but I guess I'm having trouble combining the two (I'm a newbie here, so sorry if this is really basic!)
Here's what I have so far:
struct college_class
{
char dept_classnumber;
char class_name;
char term_year;
char is_required;
char comments;
char grade;
}
college_class[60]
int main()
{
int n;
char again;
for(n=0;n<60;n++)
{
do
{
cout<<"Enter department and class number (e.g. CS162): ";
getline (cin,college_class[n].dept_classnumber);
cout<<"Enter class name (e.g. Intro to Computer Science): ";
getline (cin,college_class[n].class_name);
cout<<"Enter the term and year the class was/will be taken: ";
getline (cin, college_class[n],term_year;
cout<<"Enter whether or not this class is required for your major: ";
getline (cin,college_class[n],is_required);
cout<<"Enter any additional comments here: ";
getline (cin, college_class[n],comments);
cout<<"Would you like to enter another class?(y/n)";
cin>>again;
}
while(again == 'y' || again == 'Y' && i<60)
}
Is this the right direction in terms of getting the user input? My other question is, how do you incorporate the external file into this so that everything the user inputs is stored into the file? Sorry if this is a little vague, and I'm obviously not looking for my homework to be done for me - I'm just looking for a little direction to get started here.
I know that writing on a text file looks like this, for example:
ofstream my file ("example");
if(myfile.is_open()))
{
myfile <<"blah blah blah. \n";
myfile.close();
}
...I'm just not sure how to make this work for arrays of structs.
There are multiple things wrong with you code.
First of all, you have to create a variable for your college_class array.
Eg.:
college_class myCollegeClass[60]
and use that when asking input
getline (cin, myCollegeClass[n].term_year;)
you accidentally used commas on some lines there, watch out for that
Furthermore, a char can only hold one character, which won't be enough if you want to hold the full class name, use strings in your struct.
struct college_class
{
string class_name;
...
}
You used a nested loop there, which will repeat your questions 60 times, regardless if you said you didn't want to input anything else.
I'd suggest
int i=0;
char again = 'y';
while(again != 'n' && again != 'N' && i<60)
{
...
i++
}
As for the file, after you have your inputs, just loop though your myCollegeClass array and write the data to the file. Eg.:
myfile << myCollegeClass[i].class_name;

Arrays of Structures and External Files in C++

poSo, I've made some progress with a question I asked earlier, but I have one more question. I'll copy and paste the description of the assignment from my earlier question: So I'm working on a homework assignment for my CS162 class which requires me to make a program that allows the user to input their class plan for college. The user inputs classes they have taken, are currently taken, and/or plan on taking, with the categories of: department/class number, class name, term/year, whether or not the class is required for their major, and any additional comments. Then, the program is supposed to store this invermation with external data files so that the classes are stored and won't be lost. The program should be able to store up to 60 classes in memory.
Now, I've set up everything correctly (I believe) with my arrays of structures; but what I'm still struggling with is the reading of this information into an external file to be stored. Here's what I have so far:
struct college_class
{
string dept_classnumber;
string class_name;
string term_year;
string is_required;
string comments;
string grade;
}
college_class myCollegeClass[60];
int main()
{
int i=0;'
char again='y';
while(again != 'n' && again != 'N' && i<60)
{
cout<<"Enter department and class number (e.g. "CS162"): ";
getline (cin,my CollegeClass[n].dept_classnumber);
cout<<"Enter class name (e.g. "Intro to Computer Science"): ";
getline (cin,myCollegeClass[n].class_name);
cout<<"Enter the term and year the class was/will be taken: ";
getline (cin, myCollegeClass[n].term_year;
cout<<"Enter whether or not this class is required for your major: ";
getline (cin,myCollegeClass[n].is_required);
cout<<"Enter any additional comments here: ";
getline (cin, myCollegeClass[n].comments);
cout<<"Would you like to enter another class?(y/n)";
cin>>again;
i++;
}
ofstream myfile("classes");
if(myfile.is_open())
{
/*I know that I need to loop through my myCollegeClass here, but I'm not sure how to do it*/
{
myfile<<myCollegeClass[i].dept_classnumber;
myfile<<myCollegeClass[i].class_name;
myfile<<myCollegeClass[i].term_year;
myfile<<myCollegeClass[i].is_required;
myfile<<myCollegeClass[i].comments;
}
}
else cout<<"Unable to open file";
return 0;
}
Can anyone help me with the external file aspect of this? Thanks so much for the help (in advance)
First of all you need to change your variable from n which doesn't apper anywhere to i in your while loop.
From this:
getline (cin,my CollegeClass[n].dept_classnumber);
to this:
getline (cin,my CollegeClass[i].dept_classnumber);
Secondly add a for loop to save every class. The loop should look like this:
for(int j=0;j<i;++j){
myfile<<myCollegeClass[j].dept_classnumber<<endl;
myfile<<myCollegeClass[j].class_name<<endl;
myfile<<myCollegeClass[j].term_year<<endl;
myfile<<myCollegeClass[j].is_required<<endl;
myfile<<myCollegeClass[j].comments<<endl;
}
Don't forget to close the file with:
myfile.close();
Futhermore you should name your variable with names that say for what purpose they are used.
Here you can change i to numberOfClasses it woudl look much better.

C++: how do I check if the cin buffer is empty?

How do you check to see if the user didn't input anything at a cin command and simply pressed enter?
When reading from std::cin, it's preferable not to use the stream extraction operator >> as this can have all sorts of nasty side effects. For example, if you have this code:
std::string name;
std::cin >> name;
And I enter John Doe, then the line to read from cin will just hold the value John, leaving Doe behind to be read by some future read operation. Similarly, if I were to write:
int myInteger;
std::cin >> myInteger;
And I then type in John Doe, then cin will enter an error state and will refuse to do any future read operations until you explicitly clear its error state and flush the characters that caused the error.
A better way to do user input is to use std::getline to read characters from the keyboard until the user hits enter. For example:
std::string name;
getline(std::cin, name); // getline doesn't need the std:: prefix here because C++ has ADL.
ADL stands for argument-dependent lookup. Now, if I enter John Doe, the value of name will be John Doe and there won't be any data left around in cin. Moreover, this also lets you test if the user just hit enter:
std::string name;
getline(std::cin, name);
if (name.empty()) {
/* ... nothing entered ... */
}
The drawback of using this approach is that if you want to read in a formatted data line, an int or a double you'll have to parse the representation out of the string. I personally think this is worth it because it gives you a more fine-grained control of what to do if the user enters something invalid and "guards" cin from ever entering a fail state.
I teach a C++ programming course, and have some lecture notes about the streams library that goes into a fair amount of detail about how to read formatted data from cin in a safe way (mostly at the end of the chapter). I'm not sure how useful you'll find this, but in case it's helpful I thought I'd post the link.
Hope this helps!
cin will not continue with the program unless the user enters at least 1 character (enter doesn't count). If the user doesn't give ANY input, cin will just keep waiting for the user to give input and then press enter.
The Simple way >>
{
char X=0; // ASCII( 0 ) means a NULL value
cin>>X;
if(X==0 || X==10) // ASCII( 10 ) means ENTER
cout<<"User din't enter ANYTHING !! ";
}
But a simple problem is....
cin just won't allow you to move further without entering a character
by character here i mean a DIGIT or alphabet or special symbol , not space, enter null etc
Hope this solves your problem, if it doesn't, I'll be glad to help just let me know.
int main(){
string str[100];
std::cout<<"Hello how are you ? \n";
std::cin>>str;
if(str.length() > 0){
// If input is seen
}
else{
// If input is not seen
}
}
Any problem let me know.

Simple File I/O in C++ - Never Exits This Loop?

I'm a programming student in my second OOP class, my first class was taught in C# and this class is taught in C++. To get our feet wet in C++, our professor has asked us to write a rather large program with File I/O. The problem is, I have a small part of my program that is not working, at least, not for me. The project requires that we code a loop to test if the file could be opened successfully, and the loop I have written doesn't seem to be working.
I don't get any compiler errors, but when I enter in the path to the file, either relative or absolute, it says it's invalid. I have a feeling it has something to do with my conditions in my do-while loop, but I can't pinpoint it.
I don't mean to bring my homework to SO, but I've been scratching my head for two+ hours, and I can't seem to figure this out.
Would you mind helping me fix my loop? And maybe explain what it is that I'm doing wrong? I want to learn.
Thanks!
Code:
Rainfall rData;
ifstream actualReader;
ifstream averageReader;
string aRDataLoc;
char response = 'a';
const int KILL_VALUE = 1;
double actualRainfallD;
double actualRainfallPassedArray[ARRAY_CAPACITY];
double averageRainfallPassedArray[ARRAY_CAPACITY];
int i = 0;
do
{
actualReader.clear();
cout << "\nPlease enter in the path to the file containing the actual rainfall data." << endl;
cout << "Path to file: ";
cin >> aRDataLoc;
actualReader.open(aRDataLoc.c_str());
if (!actualReader.is_open())
{
cout << "Invalid file path! Would you like to enter in a new file path?(y/n): ";
cin >> response;
if (response == 'n') { exit(KILL_VALUE); }
}
}while (!actualReader.is_open() && response == 'y');
I don't know what input you are giving to cin, but be aware that cin will stop at the first whitespace character it encounters. For example, if you give as input the following:
C:\Program Files\directory
then aRDataLog would have the value C:\Program .
In order to read the whole line, you could use getline.
Check also this post.
While I'm not exactly sure what the issue is here, it might be a good idea to print what you're getting from std::cin to ensure you're getting what you're expecting.
you need to put actualReader.close call in else, as the file has open handles and it is not available for open again