Jump to content

if any student is named Jackson, help please

- - - - -

  • Please log in to reply
9 replies to this topic

#1
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Hi :)

The code below is incomplete but still you can run it. There is some problem with it. When I have entered student #1's data it cycles through the loop automatically without asking for any data input. Please help me to solve the problem. Thanks.


// if_any_student_named_jackson_heights.cpp

// check if any student is named Jackson Heights


#include <iostream>

#include <cstdlib>

#include <cstring>

#include <iomanip>


using namespace std;


struct Student {char name[16]; int rollno; string sex; int age; float marks;};


const int N = 5;


Student stud[N];


int main()

{


        int i;


        cout << "enter the students' details below\n\n";


        for (i=0; i<N; i++)

        {

                cout << "enter student #" << (i+1) << "\'s name: ";

                cin.get(stud[i].name, 16);

                cout << "enter roll no.: ";

                cin >> stud[i].rollno;

                cout << "enter sex: ";

                cin >> stud[i].sex;

                cout << "enter age: ";

                cin >> stud[i].age;

                cout << "enter marks: ";

                cin >> stud[i].marks;

        }



        system("pause");

        return 0;


}


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#2
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
I think I have solved the problem in the code in my first post above. Now I face another problem. Please have a look on the output below. It should be "#2" instead. Where am I going wrong? Please help me. Thanks.


// if_any_student_named_jackson_heights.cpp

// check if any student is named Jackson Heights


#include <iostream>

#include <cstdlib>

#include <cstring>

#include <iomanip>


using namespace std;


struct Student {char name[16]; int rollno; string sex; int age; float marks;};


const int N = 2;


Student stud[N];


int main()

{


        int i; char name_search[20];


        cout << "enter the students' details below\n\n";


        for (i=0; i<N; i++)

        {

                cout << "\nenter student #" << (i+1) << "\'s name: ";

                cin.get(stud[i].name, 16);

                cout << "enter roll no.: ";

                cin >> stud[i].rollno;

                cout << "enter sex: ";

                cin >> stud[i].sex;

                cout << "enter age: ";

                cin >> stud[i].age;

                cout << "enter marks: ";

                cin >> stud[i].marks;

                cin.ignore();

        }


        cout << "\n\nenter the name to be searched for: ";

        cin.get(name_search, 20);


        for (i=0; i<N; i++)

        {

                if (stud[i].name == name_search)

                {

                        break;

                }

        }


        cout << "the student at #" << (i+1) << " in the record"

             << " matches the entered name\n\n";



        system("pause");

        return 0;


}


OUTPUT

enter the students' details below



enter student #1's name: jackson

enter roll no.: 1

enter sex: male

enter age: 18

enter marks: 99


enter student #2's name: heights

enter roll no.: 2

enter sex: male

enter age: 19

enter marks: 100



enter the name to be searched for: heights


the student at [B][SIZE="4"][COLOR="red"]#3[/COLOR][/SIZE][/B] in the record matches the entered name


Press any key to continue . . .


I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#3
AKMafia001

AKMafia001

    Programmer

  • Members
  • PipPipPipPip
  • 119 posts
Let's have a look to the basics of for loop.
i) The loop is initialized.
ii) Condition is checked.
a) If false, exit.
b) If true, execute the body of the loop once and increment at the end.
iii) Repeat step (ii).

Now your code,
Suppose N is 2, and the entered info is,

enter student #1's name: jackson

enter roll no.: 1

enter sex: male

enter age: 18

enter marks: 99


enter student #2's name: heights

enter roll no.: 2

enter sex: male

enter age: 19

enter marks: 100


Now let's switch to the search phase,
for (i=0; i<N; i++)

        {

                if (stud[i].name == name_search)

                {

                        break;

                }

        }


i) The loop is initialized. i.e. i = 0.
ii) Condition is checked. i.e. i < N, where N = 2(0 < 2).
a) If false, exit. It's not false so it will not exit.
b) If true, execute the body of the loop once and increment at the end. Now i = 1.
iii) Repeat step (ii).

ii) Condition is checked. i.e. i < N, where N = 2(1 < 2).
a) If false, exit. It's not false so it will not exit.
b) If true, execute the body of the loop once and increment at the end. Now i = 2.
iii) Repeat step (ii).

ii) Condition is checked. i.e. i < N, where N = 2(2 < 2).
a) If false, exit. Yes!

Remember while exiting from the loop i = 2.


 if (stud[i].name == name_search)

                {

                        break;

                }


You have typed the above script is for the sake of terminating the loop. But the loop is not terminating and going till the end.

Then when you type the code below, it prints 3 because i is 2 already and ( i + 1 ) print 3.

cout << "the student at #" << (i+1) << " in the record"

             << " matches the entered name\n\n";


Do you think if (stud[i].name == name_search) will match ?
I think i'm able to write a code for printing "Hello, World!". Proud of that!

#4
AKMafia001

AKMafia001

    Programmer

  • Members
  • PipPipPipPip
  • 119 posts
If you have got no answer so i will tell you that they will never match and that's why the break doesn't works and it goes till the end.

if (stud[i].name == name_search)

This if statment will be false always. At the end of program you are just printing the number nothing else there. You haven't searched for any name.
In these situation whether it is a string or an integer value don't match them directly.
For integer you can simply write,

if((int1 % int2) == 0)

OR

if((int1 / int2) == 1)

In this way it will work. While for string you can use the function strcmp() to compare them. e.g,

if(strcmp(str1,str2) == 0)


So your code will work if,

for (i=0; i<N; i++)

        {

                if (strcmp(stud[i].name,name_search)==0)

		{

			cout << "the student at #" << (i+1) << " in the record"

            		 << " matches the entered name\n\n";


                	break;

                }

		

        }


You can print it at the end of the program also.
I think i'm able to write a code for printing "Hello, World!". Proud of that!

#5
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Thank you, AKM. Now I understand the inner working of the for loop. That's good for me.

AKMafia001 said:

Do you think if (stud[i].name == name_search) will match ?

Yes, I think they will match? Won't they? If no, what's the reason? Is this because one's size is [16] and other's [20]?

Regards
Jackson
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#6
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
They won't match because you're comparing addresses of two variables and obviously two variables cannot exist on same address (they can however point to same address so in some cases that could evaluate to true). This is because you're using an array of char's, if you want to compare strings like this you'll need a std::string class, or like AKMafia said, use strcmp() function.
A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#7
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
It would be more advisable to use the std::string container, only use c strings when you need to (although learn them well, I believe you have run in to the strcmp problem in the past, remember that cstrings are an array of chars and not an object, thus == is not overloaded in C++ and will not match)
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#8
jackson6612

jackson6612

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 304 posts
Thanks a lot, everyone.

I'm learning C-strings so I can't use C++ strings, otherwise, probably, teacher would cross my work.

if (strcmp(stud[i].name,name_search)==[B][SIZE="3"][COLOR="red"]0[/COLOR][/SIZE][/B])

The if block is executed when the condition is evaluated to be true, that is "1" and "0" for false (the condition expression inside the parentheses is converted to bool type). So, why is "0" used above in the if condition expression for strcmp? Please let me know. Thanks.
I'm an outright beginner, learning C++. Using Win XP Pro and Code::Blocks. Be nice to me, please.:)

#9
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
Consider this:

if (0 == 0)

    std::cout << "it's true!";

If you run this piece of code, you will the above output. Why? Because 0 is equal to 0 and this is true. The other thing you need to know is the return value of strcmp() function and is as following: 0 is strings are equal, any positive number means the first position of unmatched character in first string, and negative number means the same for second string (first position where they don't match).

As a little brain teaser, consider the following Python code (in Python you can override values of true and false):

>>> True == True    # these are input lines

True    # these are output lines

>>> False == False

True

>>> True = False    # note the assignment here

>>> True == False

True

>>> True == True

True


A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#10
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200

jackson6612 said:

So, why is "0" used above in the if condition expression for strcmp? Please let me know. Thanks.

It returns the lexical difference between the two strings, I would write it as the following personally:
int mystrcmp(const char* a, const char* b) {

    while (*a && *a == *b) { //not null && letters are the same (value,) so we ignore

        a++, b++;

    }

    return *a - *b;

}

You can think of the two strings as positions in an imaginary dictionary. This function will return the ASCII difference in the two strings.

For example if you used my function mystrcmp("abcdef", "abcabc")

a == a, skip

b == b, skip

c == c, skip

d != a, so return ASCII 'd' - 'a'

This will return the integer 3, as in 'd' is 3 ASCII positions past 'a'.

Most libraries cap the result at -1, 0, or 1 so my result will be returned just as 1 in the original strcmp as we have no need to know anything more than that.

Why do we use this?

You can imagine the sort() method, if string b is before string a, then string b is sorted upwards. It is a simple method, although you could imagine how simple sorting functions would have trouble if the function returned just "true" or "false", it would require more comparison. Much of the existing standard libraries would rely on this behavior, as it is well optimized (direct pointer comparisons)

It is the only downside to this function, == 0 must be done to return true (as in lexically different) rather than "true"

Notes: In ASCII, numbers are before capitals, and non-capitals are after capitals. You may wish to use stricmp or strcasecmp function to compare "Jackson" to be the same as "jackson", (although these are unfortunately not standard, just use a tolower() function on the whole string first to emulate this)

Another note, you have stated this:

Jackson said:

the condition expression inside the parentheses is converted to bool type
Although there is a bool type in C++, it still remains an integral type (any non-zero value, there is no conversion to "false" or "true" for the if statement, false would translate to 0 for example not the other way around)
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users