explanation

found this code but still dont understand it
i understand most of the main() function part but i'm not familiar with the string noBlanks part

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 <sstream>
#include <string>
#include <cctype>
using namespace std;

string noBlanks( string str )
{
   string result;
   for ( char c : str ) if ( !isspace( c ) )  result += c;
   return result;
}

int main()
{
   int num;
   int sum = 0;
   string line;

   cout << "Input an expression: ";
   getline( cin, line );
   line = noBlanks( line );
   stringstream ss( line );
   while ( ss >> num ) sum += num;

   cout << "Result is " << sum << '\n';
}
1
2
3
4
5
6
7
8
9
10
11
12
13
string noBlanks( string str )
{
   string result;  // create an empty string

   for ( char c : str )   // for every char in the input string named "str"...
  { 
     if ( !isspace( c ) )   //  if that char is not a space...
     {
         result += c;  // put a copy of that char on the end of the string named "result"
      }
  }
   return result;
}


This function copies every character in the input string to a new string, EXCEPT the spaces, and then returns that new string.
It comes from here, for context:
http://www.cplusplus.com/forum/beginner/231860/#msg1045577

But @Repeater has done a far better job of commenting my code than I did!


@ZLAPQM: I think you could have continued your previous thread at
http://www.cplusplus.com/forum/beginner/232770/#msg1047394
Last edited on
Topic archived. No new replies allowed.