0

I have an array of 20 strings with a maximum of 81 characters that will be populated by the user, how do I go about removing the excess null characters at the end should the users input be > 81 characters?

I've tried to search for solutions to this, but most seem to require me to know how many characters the user has input into the string before the program is run.

int main()
{
    string strings[20];

    cout << "Enter up to 20 strings, press enter when done: ";

    input(strings);

    for (int i = 0; i < 20; i++)
    {
        if (strings[i] == "\0")
            break;
        else
        {
            strings[i].resize(81);
            cout << "Here is string" << i << ": " << endl << strings[i] << endl;
            menu(strings[i]);
        }

    }

void input(string strings[])
{
    for (int i = 0; i < 20; i++)
    {
        getline(cin, strings[i]);
        if (strings[i] == "\0")
            break;
    }
}
4
  • 4
    "how do I go about removing the excess null characters at the end should the users input" What excess null characters? Strings that you read via std::getline will not contain any null characters.. Commented Oct 22, 2019 at 17:01
  • You are either taking unusual input or handling the input strangely to make this a problem. Can you please expand on the problem to demonstrate how you are using the input and add a sample input set? Commented Oct 22, 2019 at 17:22
  • why do you think that you have to remove null-characters? I have the feeling this is a xy problem where X actually is no problem. What makes you think there is a problem? Commented Oct 22, 2019 at 18:19
  • 1
    strings[i] == "\0" is an unusual way of doing strings[i].empty() (empty). Commented Oct 22, 2019 at 18:49

1 Answer 1

1

Have you tried the following?

strings[i] = strings[i].substr(0, 81)

I haven't worked with C++ in awhile but this should just trim the input to the first 81 characters. Better yet, apply this when you first get the input or return a user input error to the user if too long.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.