2

Create a program titled str_compress.cpp. This program will take a sentence input and remove all spaces from the sentence. (A good first step in encryption programs) Make sure that both the input and output strings are all stored in a single variable each. Do not use numbers or symbols. Include both upper-case and lower-case letters. Account for cases with multiple spaces anywhere.

This is what I have so far:

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

int main()
{
    int i = 0, j = 0, len;
    string str;

    cout << "Enter string: ";
    getline(cin, str);

    len = str.length();

    for (i = 0; i < len; i++)
    {
        if (str[i] == ' ')
        {
            for (j = i; j < len; j++)
            {
                str[j] = str[j + 1];
            }
            len--;
        }
    }

    cout << str << endl;

    system("pause");
    return 0;
}

I can eliminate spaces, but only one at a time. If I copy and paste the for loop, I can remove all spaces for how many loops there are. I'm thinking that I can loop the for loop over and over until all spaces are gone, but I'm not sure how to do that. Also, I can't use anything like remove_all() or erase().

6
  • Open your C++ textbook to the chapter that explains the concepts behind iterators, and read it. After you learn, and understand, how to use iterators you will find that this task can be trivially done with just one loop, and a handful of iterators. Working it out in my head, just four statements. Commented May 21, 2020 at 1:42
  • 1
    "(A good first step in encryption programs)" Ron Howard voice: is it? Commented May 21, 2020 at 1:45
  • @SamVarshavchik I don't have a c++ text book and all my lectures have been online due too covid-19. I am not as smart as you, clearly, so maybe you could enlighten me on a trivial example Commented May 21, 2020 at 1:50
  • 2
    Nobody should expect to be able to effectively learn C++ without a textbook. C++ is the most complicated general purpose programming language in use today. Without a comprehensive textbook that gives a guided, methodical introduction to the core C++ concepts and language, you will not be able accomplish much. I can't even fathom how one would go about understanding virtual inheritance, polymorphism, templates, specialization, overloading, move semantics, etc, etc, etc... without a C++ textbook to use as a reference. Commented May 21, 2020 at 2:06
  • QF: This is my suggestion: For every line of real code in your program print something that tells you as a programmer how far the program got (and how it got there). Some people say this is a bad way of debugging. It's a complement to a full on battery of debugging tools. Commented May 21, 2020 at 2:06

3 Answers 3

4

This is a strong clue for how the authors of your exercise want you to write your code:

Make sure that both the input and output strings are all stored in a single variable each

You should make a new string:

string new_str;

Use your loop over the input string. For each char in the string, check whether it is a space. If yes, do nothing. If no, append it to the output string:

for (i = ...)
{
    char c = str[i];
    if (c != ' ')
        new_str.push_back(c);
}
Sign up to request clarification or add additional context in comments.

3 Comments

I cannot use .push_back. Is there a way to do this without?
emplace_back 🤷‍♂️
Also new_str += c. Or use stringstream new_str and then new_str << c.
3

Your loop's logic when removing a space is wrong. For instance, after removing a space, you then skip the next char in the string, which may be another space. Also, although you are decrementing the len, you don't resize the string to the new len before printing the new str value.

It should look more like this:

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

int main()
{
    size_t i, j, len;
    string str;

    cout << "Enter string: ";
    getline(cin, str);

    len = str.length();

    i = 0;
    while (i < len)
    {
        if (str[i] == ' ')
        {
            for (j = i + 1; j < len; ++j)
            {
                str[j - 1] = str[j];
            }
            --len;
        }
        else
            ++i;
    }

    str.resize(len);
    cout << str << endl;

    /* or, if you are not allowed to use resize():
    cout.write(str.c_str(), len);
    cout << endl;
    */

    /* or, if you are not allowed to use write():
    if (len < str.length())
        str[len] = '\0';
    cout << str.c_str() << endl;
    */

    system("pause");
    return 0;
}

Live Demo

However, your instructions do say to "Make sure that both the input and output strings are all stored in a single variable each", which implies that separate std::string variables should be used for input and output, eg:

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

int main()
{
    size_t i, j, len;
    string str, str2;

    cout << "Enter string: ";
    getline(cin, str);

    str2 = str;
    len = str2.length();

    i = 0;
    while (i < len)
    {
        if (str2[i] == ' ')
        {
            for (j = i + 1; j < len; ++j)
            {
                str2[j - 1] = str2[j];
            }
            --len;
        }
        else
            ++i;
    }

    str2.resize(len);
    cout << str2 << endl;

    /* or:
    cout.write(str2.c_str(), len);
    cout << endl;
    */

    /* or:
    if (len < str2.length())
        str2[len] = '\0';
    cout << str2.c_str() << endl;
    */

    system("pause");
    return 0;
}

Live Demo

Alternatively:

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

int main()
{
    size_t i, j, len;
    string str, str2;

    cout << "Enter string: ";
    getline(cin, str);

    len = str.length();
    str2.reserve(len);

    for(i = 0; i < len; ++i)
    {
        char ch = str[i];
        if (ch != ' ')
            str2 += ch;
    }

    cout << str2 << endl;

    system("pause");
    return 0;
}

Live Demo

6 Comments

thank you for this. It has helped a bunch. Is there a way to resize the len variable without using .resize()? Not something the teacher is allowing
You can use ostream::write() instead of operator<<, eg: cout.write(str.c_str(), len); cout << endl; Your teacher is really restricting you too much. There is no point in using std::string if you are not allowed to leverage its strengths. This is not teaching you proper C++.
agreed. I can't use hardly anything which makes the most trivial problems so complicated. Also why I get so much lash back from people when I post these types of problems. cout.write() is also something that has not been taught. This is why I am having so much trouble with this
cout << ... and cout.write(...) are the only two ways you can write to cout. If you can't use cout.write() then your only remaining choice is to explicitly null-terminate the str after modifying it and then use cout << str.c_str(). I updated my answer to show this.
How do you know what is allowed and what is not? Surely you don't have a list of disallowed things? If you have a list of allowed things, you may think along the lines of "How can I resize a string using only X, Y and Z"? Or even ask separate questions on that. That may make some interesting mind-bending exercises for people who are used to full power of C++.
|
0

This is what worked for me. Thank you everyone for the help!!

int main()
{
int i, j, len;
string str, str2;

cout << "Enter string: ";
getline(cin, str);

len = str.length();

for (i = 0; i < len; ++i)
{
    char ch = str[i];
    if (ch != ' ')
        str2 += ch;
}

cout << str2 << endl;

system("pause");
return 0;
}

Comments

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.