string to int, removing whitespace

I am doing questions on hackerrank, and have been asked to make a loop, which I have been able to do easy enough. But the starter code is quite unfamiliar to me. The input is passed in as a string and converted to an int. Ive looked up and learned what a few things are, such as not1 and isspace. But I am really confused at what the code (ptr_fun<int, int> is doing. I have looked it up but dont really understand what it is saying. I have not been learning for very long so find it difficult sometimes to understand the documentation. Can someone explain what this does in simple terms?

Also is this still used in c++, or is this more c stuff?

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
  #include <bits/stdc++.h>

using namespace std;

string ltrim(const string &);
string rtrim(const string &);



int main()
{
    string n_temp;
    getline(cin, n_temp);

    int n = stoi(ltrim(rtrim(n_temp)));
    
    for (int i = 1; i < 11; i ++)
    {
        cout << n << " x " << i << " = " << n * i << "\n";
    }

    return 0;
}

string ltrim(const string &str) {
    string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );

    return s;
}

string rtrim(const string &str) {
    string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );

    return s;
}
But I am really confused at what the code (ptr_fun<int, int> is doing.


From context, it's a call to a function that's generated from a function template. A function template defines how the compiler can create a function to operate on unknown types. In this case, ptr_fun() is obviously defined to operate on two types.

When the compiler sees ptr_fun<int, int>(isspace) it creates a version of the function ptr_fun() where both those types are int.

We have a tutorial on templates right here on this site:

https://www.cplusplus.com/doc/oldtutorial/templates/
Last edited on
It's very old C++! not1 and ptr_fun were depreciated in C++11 and removed in C++17. Hence with C++17 or the current C++20 they are not available.

It allowed a function to be passed as an argument to a templated function as a predicate - before lambdas were introduced with C++11.

ptr_fun<int, int>(isspace) meant that the specified function - isspace - takes one argument of int (first int) and returns a type int (second int).

not1() returns the complement of the specified unary predicate function ie the inverse of the result from ptr_fun() - meaning isnotspace.

Last edited on
For modern C++ code, perhaps:

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
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

std::string ltrim(const std::string&);
std::string rtrim(const std::string&);

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

	const auto n {stoi(ltrim(rtrim(n_temp)))};

	for (int i = 1; i < 11; ++i)
		std::cout << n << " x " << i << " = " << n * i << '\n';
}

std::string ltrim(const std::string& str) {
	return std::string(std::find_if(str.cbegin(), str.cend(), [](unsigned char ch) {return !std::isspace(ch); }), str.cend());
}

std::string rtrim(const std::string& str) {
	return std::string(str.cbegin(), std::find_if(str.crbegin(), str.crend(), [](unsigned char ch) {return !std::isspace(ch); }).base());
}

Last edited on
Or even without doing an explicit string to int conversion and using stream extraction:

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
#include <iostream>
#include <string>
#include <limits>
#include <cctype>

int getInt(const std::string& prm)
{
	const auto notsp {[&]() {while (std::isspace(std::cin.peek()) && std::cin.peek() != '\n') std::cin.ignore(); return std::cin.peek() != '\n'; }};
	int i {};

	while ((std::cout << prm) && (!(std::cin >> i) || notsp())) {
		std::cout << "Not an integer\n";
		std::cin.clear();
		std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}

	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	return i;
}

int main()
{
	const auto n {getInt("Enter multiplicand: ")};

	for (int i = 1; i < 11; ++i)
		std::cout << n << " x " << i << " = " << n * i << '\n';
}

Last edited on
Thank you for all the answers, they were a lot more helpful than what I was getting from the documentation.

As for some of the code being removed in c++17, is it pointless for me to be doing these questions or is it still good to learn? I am using the hackerrank site for problem solving practice but It seems like a lot of the code is, what I think is older C based stuff.
honestly I have repeatedly been steered towards hackerank by people saying it is used by recruiters / interviewers. But my experience was pretty much like yours-- it seems to use an old compiler(possibly) or old material (more likely), they want you to pay to see what you did wrong, and it is relatively unclear what they want (many problems have hidden unstated requirements).
that said, real life has a lot of hidden, unstated requirements AND the problems on the HR site are more useful (less problems like chef has to serve salisbury steak to between 1 < n < 10000000000000000 southparkians and can only cook it while juggling flaming tomatos. Find how many tomatoes chef needs to burn to serve the town if n grows exponentially as more people around the country hear about his awesome food) and more like "get some input from a user and do something useful with it".
So all in all, my take on it would be to use the problems off HR and code them with modern tools to your own satisfaction. If their site will not accept something you wrote because of an old compiler, move on. The HR problems are good. Their scoring system is both good and bad.
Last edited on
Thank you for your input jonnin, I will continue using it the way you suggested, think coding the answers will modern tools will be a good idea.
I am terrible at problem solving as well as fully understanding what a question is asking, and that's why I was enjoying using the hackerranks questions, I've not found another site that offers easier questions and explain the question well.
old textbooks are a wealth of good problems as well. The material may be outdated but the problems can be solved however you want when you do them... and you can often get old text books for very little at used book stores, and some are online for cheap as well.
I am terrible at problem solving as well as fully understanding what a question is asking


Most of us were when we first started! It gets better as understanding increases. My advice is to program, program program. The more you write programs, the better you'll become. Don't just start to code. Think about the problem, how would you solve it without a computer? What steps would you take? What data is being used - for input, output? What data structures are needed - which choices would be good in this situation? When you're thought through all of this, then do a program design. Then only once you're got a design then do you start coding. The last thing you do in programming is code!

And when you do start to code from the design, code small parts at once. Compile and test that part. Get it to compile/work before moving to code the next part. Don't code a hundred or so lines, compile it, get loads of errors and then don't know where to start to fix it. IMO you should be compiling after about 10 - 5 lines and no more than 20.
@DonnaPin

This book might be helpful in a general sense, I might order it myself :+)

https://en.wikipedia.org/wiki/How_to_Solve_It

Good Luck !!
Others books I suggest are:

'Think like a programmer' by Spraul

'How to Think Like a Programmer: Program Design Solutions For The Bewildered' by Vickers (not to be confused with 'How to Think Like a Programmer: Problem Solving for the Bewildered' by the same author!)
Topic archived. No new replies allowed.