MrDespair
MrDespair

Reputation: 151

C++ Character Array Error Handling

If I declare a string array in c++ such as

char name[10]

how would you error handle if the input is over the character limit?

Edit: My assignment says to use cstring rather than string. Input will be the person's full name.

Upvotes: 0

Views: 1252

Answers (4)

Ternary
Ternary

Reputation: 2421

I'm piecing together that your instructions say to use <cstring> so you can use strlen to check the length of the string prior to "assigning" it to your name array.

so something like...

const int MAX_NAME_LEN = 10;
char name[MAX_NAME_LEN];
// ...
// ...
if (strlen(input)+1 >= MAX_NAME_LEN) {
// can't save it, too big to store w/ null char
}
else {
// good to go
}

Upvotes: 1

IllusiveBrian
IllusiveBrian

Reputation: 3224

Since others mentioned how to do this with a predefined input string, here's a solution which reads a c-string from input:

#include <iostream>

#define BUF_SIZE 10

using namespace std;
int main()
{
    char name[BUF_SIZE];
    cin.get(name, BUF_SIZE-1);
    if (cin) //No eof
        if (cin.get() != '\n')
            cerr << "Name may not exceed " << BUF_SIZE-1 << " characters";
}

Upvotes: 0

jpo38
jpo38

Reputation: 21544

Here is an example where setName checks the size is OK before assigning the char[10] attribute.

Note char[10] can only store a 9-characters name, because you need one character to store the end-of-string.

Maybe that's what you want:

#include <iostream>
#include <cstring>
using namespace std;

#define FIXED_SIZE 10

class Dummy
{
public:
    bool setName( const char* newName )
    {
        if ( strlen( newName ) + 1 > FIXED_SIZE )
            return false;

        strcpy( name, newName );
        return true;
    }
private:
    char name[FIXED_SIZE];
};

int main()
{
    Dummy foo;

    if ( foo.setName( "ok" ) )
        std::cout << "short works" << std::endl;
    if ( foo.setName( "012345678" ) )
        std::cout << "9 chars OK,leavs space for \0" << std::endl;
    if ( !foo.setName( "0123456789" ) )
        std::cout << "10 chars not OK, needs space for \0" << std::endl;
    if ( !foo.setName( "not ok because too long" ) )
        std::cout << "long does not work" << std::endl;

    // your code goes here
    return 0;
}

Upvotes: 1

ravi
ravi

Reputation: 10733

First of all your question is not clear. Anyway I assume you want to ask for a way to ensure array index does not get out of bound.

Anything outside of that range causes undefined behavior. If the index was near the range, most probably you read your own program's memory. If the index was largely out of range, most probably your program will be killed by the operating system.

That means undefined behaviour could mean program crash, correct output etc.

Upvotes: 0

Related Questions