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;
    }
}
cVos
  • 27
  • 1
  • 5
  • 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.. – Algirdas Preidžius Oct 22 '19 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? – user4581301 Oct 22 '19 at 17:22
  • why do you think that you have to remove null-characters? I have the feeling this is a [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) where X actually is no problem. What makes you think there is a problem? – 463035818_is_not_an_ai Oct 22 '19 at 18:19
  • 1
    `strings[i] == "\0"` is an unusual way of doing `strings[i].empty()` ([empty](https://en.cppreference.com/w/cpp/string/basic_string/empty)). – Eljay Oct 22 '19 at 18:49

1 Answers1

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.

Baledin
  • 43
  • 4