开发者

C++ loop logic error?

I am having some trouble getting a C++ logic loop working. From testing, I believe it is a error in the Grades() function loop.

Basically the program is supposed to get the Names and Test Scores, which it appears to do, but the program exits right after that and I am not sure why. Just wanting to see if anyone else noticed an error in the function that could be causing the program to terminate prematurely.

// Grades
void Grades(char names[][length], double grades[][4])
{
    for(int i = 0; i < amount; i++)
    {
        cout << "Name: ";
        cin.ignore();

        cin.getline(names[i],length, '\n');

        cout << "Test Scores: ";

        for(int k = 0; k < 4; k++)
        {
            int num = 0;

            while(!(cin >> num) 开发者_JAVA技巧||
                  num  < 0 ||
                  num > 100 ) 
            {
                cout << "invalid entry." << endl;
            }

            grades[i][k] = num;
        }
    }
}


Something that bites every C++ beginner… iostream errors are "sticky" and remain until you call clear on the stream.

while(!(cin>> num) || num  < 0 || num > 100 ) 
{
    cout << "invalid entry." << endl;
    cin.clear(); // reset the error so cin evaluates to true
    cin.ignore( -1 ); // ignore the offending input
}

Also, the cin.ignore() before getline will ignore the first letter of the first name.

You should use std::string instead of char arrays.

Other than that, the program essentially works as long as the input is formatted properly. Here is the output on my system. Note that Bob's initial is cut off, and Bob and Jane have uninitialized characters after their names because the character array isn't being treated as a C-style string.

Student: ob_???_
Average Score: 60.00 Grade Letter: D

Student: jane   ???_?
Average Score: 70.00 Grade Letter: C

Student: mary
Average Score: 80.00 Grade Letter: B

Student: todd
Average Score: 90.00 Grade Letter: A

Student: alice
Average Score: 100.00 Grade Letter: A

Strangely, though, ideone.com did run the program but didn't show its output, for some reason. I have no idea.

As Evan mentions, the Windows shell exits by default if you run a command-line program by double-clicking. Run from a preexisting interactive shell to see your output. system( "pause" ); is unportable and very bad practice.


What compiler/operating system are you using?

Sometimes it's necessary to add a system("pause"); call before you return from main. This is often true if you're compiling from an IDE than runs the program directly. You could avoid the problem by running it directly from the command line/bash/etc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜