If you have a function that will extract an integer and include that integer in the output of a sum of the .length()
and the integer, form all of your output in the function itself rather than complicating things and losing control of the initial input by doing part of the input in main()
and part in your function.
Approaching things in that manner you put complete control over your output in a single function. For example in your case, if there was no integer found how would you "un-output" the length?
Putting those changes in place, your function could be similar to:
void getint (std::string s)
{
int val, /* var to hold int value */
found = 0; /* flag indicating if int was found */
size_t len = s.length(); /* get length of s */
std::string tmp; /* temporary string to read into from ss */
std::stringstream ss (s); /* create stringstream from string */
while (ss >> tmp) { /* read from ss */
try { /* stoi must have exception handler */
val = stoi (tmp); /* attempt conversion */
found = 1; /* on success set found flag */
break; /* break loop */
}
catch (const std::exception & e) { /* catch exception get next word */
continue;
}
}
if (found) /* if integer found, output your sum */
std::cout << len << " + " << val << " = " << len + val << '\n';
else /* otherwise handle error */
std::cerr << "error: no integer value in input.\n";
}
(note: the only error handling needed if no conversion takes place is to get the next word. Any output will just add lines between the input and your desired output)
An example program utilizing the function could be:
#include <iostream>
#include <sstream>
#include <string>
void getint (std::string s)
{
int val, /* var to hold int value */
found = 0; /* flag indicating if int was found */
size_t len = s.length(); /* get length of s */
std::string tmp; /* temporary string to read into from ss */
std::stringstream ss (s); /* create stringstream from string */
while (ss >> tmp) { /* read from ss */
try { /* stoi must have exception handler */
val = stoi (tmp); /* attempt conversion */
found = 1; /* on success set found flag */
break; /* break loop */
}
catch (const std::exception & e) { /* catch exception get next word */
continue;
}
}
if (found) /* if integer found, output your sum */
std::cout << len << " + " << val << " = " << len + val << '\n';
else /* otherwise handle error */
std::cerr << "error: no integer value in input.\n";
}
int main (void) {
std::string s;
if (getline (std::cin, s))
getint (s);
else
std::cerr << "stream error or user canceled.\n";
}
Example Use/Output
$ ./bin/lengthaddition
I love 6
8 + 6 = 14
with no integer in input
$ ./bin/lengthaddition
I love B
error: no integer value in input.
Look things over and let me know if you have further questions.