How can I remove spaces after an integer confirmation of a string evaluated by a function?

Hello,

I have coded a function that confirms whether a string of chars is an int or not. But how can I code it to remove the spaces from the string before or after evaluation by the notanint function?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <iostream>
#include <string>
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */

using namespace std;

int main()
{

int getanInt(); // function declaration (prototype)
int value;

cout << "Enter an integer value: ";

value = getanInt();

cout << "The integer entered is: " << value << endl;

    return 0;
}

int getanInt()
{

bool isvalidInt(string); // function declaration (prototype)
bool notanint_spaces_not_removed = true;
bool int_spaces_not_removed = true;
bool int_spaces_removed = false;
string svalue;
string sval_spaces_not_removed;
string sval_spaces_removed;

while (notanint_spaces_not_removed)
{
    try
    {
        cin >> svalue; // accept a string input

        if (!isvalidInt(svalue)) throw svalue;
        }
            catch (string e)
        {
            cout << "Invalid integer - Please reenter: ";

            continue; // send control to the while statement
        }

notanint_spaces_not_removed = false;

}

while (int_spaces_not_removed == true && int_spaces_removed == false)
{
    for (int i = 0; i < svalue.length(); i++)
    {
         sval_spaces_not_removed.at(i)=svalue.at(i);
    }

    for (int i = 0; i < sval_spaces_not_removed.length(); i++)
    {
        if (!isspace(sval_spaces_not_removed.at(i)))
        {
            sval_spaces_removed.at(i) = sval_spaces_not_removed.at(i);
        }
    }

    int_spaces_removed = true;
}

cout << "the new string with spaces removed is" << sval_spaces_removed <<endl;

return atoi(sval_spaces_removed.c_str()); // convert to an integer

}

bool isvalidInt(string str)
{

int start = 0;
int i;
bool valid = true; // assume a valid
bool sign = false; // assume no sign
bool spaces = true; // assume spaces

// check for an empty string

if (int(str.length()) == 0) valid = false;

// check for a leading sign

if (str.at(0) == '-'|| str.at(0) == '+')
{
    sign = true;
    start = 1; // start checking for digits after the sign
}

// check that there is at least one character after the sign

if (sign && int(str.length()) == 1)

    valid = false;

// now check the string, which you know
// has at least one non-sign character

i = start;

while(valid && i < int(str.length()))
{

    if(!isdigit(str.at(i)))
    {
        valid = false; //found a non-digit character

        cout << "found a non-digit character" << endl;
    }

    i++; // move to next character

}

while (valid && i < int (str.length()))
{
    if (!isspace(str.at(i)))
        {
            valid = false;

            cout << "found a space" << endl;
        }

        i++;
}

return valid;
}
.
I think I know what you are asking. But just to be sure. Could you include some example inputs and outputs?

That is...

Expected input: foo bar
Expected output: foobar

Current input: foo bar
Current output: foo b a r


first, try to use <cstdio> and <cstdlib> ... what you have works on most compilers under most settings but some more strict settings or old compilers can reject it. <cstring> is not <string.h> though (its an exception to the rule)

second, there is an eatwhite function that does this (it may be specific to visual studio, though) and some other freebies that do it as well on various platforms.

There are lots and lots of ways to do this on char arrays. One very simple way is to copy the string from one into another and eliminate the offending character:

y = 0;
for( x = 0; x < strlen(buf1); x++)
if(buf1[x] != ' ')
buf2[y++] = buf1[x];
buf2[y] = 0;


depending on exactly what you are doing, you can also take your number back into a clean string with sprintf if you happen to need/use it as a number anywhere in the code (I shamefully didn't read all that).

Unless this is a learning exercise, you are doing way too much work. I am going to assume it is practice/homework though, unless you ask for more.

Last edited on
But how can I code it to remove the spaces from the string before or after evaluation by the notanint function?

Since you're using the extraction operator>> to get your string you normally won't have any whitespace characters in front of or behind the string. Remember by default the extraction operator stops processing a string when it encounters a whitespace character, and it also skips leading whitespace before the string. But realize that any characters after the first whitespace character will be left in the input buffer for the next input operation. You probably should be using getline() instead of the extraction operator>> to insure you get the whole line that the user enters.

Also since you're using a std::string you can probably simplify the logic of your functions if you use some of the string functions to "search" for improper characters in your string. Look at functions like std::string.find_first_not_of(), .find_first_of(), etc as examples.

Lastly you should be using stoi() (requires a recent C++ compatible compiler compiling as using C++11 or greater standard) instead of atoi(). The stoi() function will also catch some errors you don't appear to be checking, for instance it will catch a value that is too large for your int type if entered.

Hello all

I am just teaching myself C++. Used to use it at uni so just re-visting my old textbooks. So it is just an exercise.

@Bdanielz
I am trying to get this

Input 1. 555 5555 555
outputs 1

So turning a string of numbers into a valid int. Just the added challenge of removing the spaces.

Hello,

@Bdaneilz

I tried your solution but ended up with an out of range error :(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <iostream>
#include <string>
#include <stdio.h>      /* printf, fgets */
#include <stdlib.h>     /* atoi */
#include <cstdio>
#include <cstdlib>
#include <string.h>

using namespace std;

int getanInt(); // function declaration (prototype)

int main()
{

int value;

cout << "Enter an integer value: ";

value = getanInt();

cout << "The integer entered is: " << value << endl;

    return 0;
}

int getanInt()
{

bool isvalidInt(string); // function declaration (prototype)
bool notanint = true;

string svalue;
string svalue_new;
char buf1[512];
char buf2[512];

while (notanint)
{
    try
    {
        getline (cin,svalue); // accept a string input

        for (int i = 0; i < svalue.length(); i++)
        {
            buf1[i] = svalue.at(i);
        }

        cout << "Now putting the string into a char array"<<endl;

        int y = 0;
        int x = 0;

        for (int x = 0; x < strlen(buf1); x++) //removing spaces from charr array
        {
            if(buf1[x] != ' ')
            {
                buf2[x] = buf1[x];
                buf2[x] = 0;
            }
        }

        // Now re-insert the char array back into the svalue string for further evaluation
        for (int i = 0; i < strlen(buf2); i++)
        {
            svalue_new.at(i) = buf2[i];
        }

        cout << "New String is now" << svalue_new <<endl;


        if (!isvalidInt(svalue_new)) throw svalue_new;
        }
            catch (string e)
        {
            cout << "Invalid integer - Please reenter: ";

            continue; // send control to the while statement
        }

notanint = false;

}

return atoi(svalue.c_str()); // convert to an integer

}

bool isvalidInt(string str)
{

int start = 0;
int i;
bool valid = true; // assume a valid
bool sign = false; // assume no sign

// check for an empty string

if (int(str.length()) == 0) valid = false;

// check for a leading sign

if (str.at(0) == '-'|| str.at(0) == '+')
{
    sign = true;
    start = 1; // start checking for digits after the sign
}

// check that there is at least one character after the sign

if (sign && int(str.length()) == 1)

    valid = false;

// now check the string, which you know
// has at least one non-sign character

i = start;

while(valid && i < int(str.length()))
{

    if(!isdigit(str.at(i)))
    {
        valid = false; //found a non-digit character
    }


    i++; // move to next character

}

return valid;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* @Bdanielz
I am trying to get this

Input 1. 555 5555 555
outputs 1 */

#include <iostream>
#include <string>
#include <cctype>

std::string do_the_thing(const std::string& s) {
    auto it = s.begin();

    // skip beginning whitespace
    while (it != s.end() && std::isspace(*it)) ++it;

    // Initial character may be numeric/+/-
    if (it == s.end() || (*it != '+' && *it != '-' && !std::isdigit(*it)))
        return std::string{};

    // skip past the digits
    while (++it != s.end() && std::isdigit(*it));

    // ensure it wasn't a lonely +/-
    if (!std::isdigit(*(it - 1))) return std::string{};

    return std::string(s.begin(), it);
}


int main() {
    std::string text;
    getline(std::cin, text);

    auto result = do_the_thing(text);

    std::cout << "Input : \"" << text << "\"\n";
    std::cout << "Result: \"" << result << "\"\n";
}
Last edited on
Just to be clear. I did not offer any solution here. I was asking about what your inputs and outputs were.
Hi Bdanielz,

That's great. But I haven't started on pointers etc yet. I'm just learning C++ off my own back revisiting some old uni courses.
Topic archived. No new replies allowed.