I'm learning C++ and wrote a function to remove all the spaces and tabs at the beginning of the input string. It removes them until it find a character different of space and tabs.
In the first version I have mixed C and C++ code and someone has told me that this is a bad coding style, but in the second version I have tried to use only C++ code.
Did I do well?
#include <fstream>
#include <ios>
#include <iostream>
#include <string>
std::string trimLeft(const std::string& input) {
if ((input.empty()) ||
((input.at(0) != ' ') && (input.at(0) != '\t')))
return input;
else {
char * tab2 = new char[input.length() + 1];
char *trimmed = new char[input.length() + 1];
strcpy(tab2, input.c_str());
bool skip = true;
size_t pos = 0;
for (size_t i = 0; i < (input.length() + 1); i++) {
if (skip) {
if ((tab2[i] == ' ') || (tab2[i] == '\t'))
continue;
else {
skip = false;
trimmed[pos] = tab2[i];
pos++;
}
}
else {
trimmed[pos] = tab2[i];
if (tab2[i] == '\0')
break;
else
pos++;
}
}
std::string stringTrimmed(trimmed);
return stringTrimmed;
}
So, I have tried to implement it using only C++ strings:
#include <fstream>
#include <ios>
#include <iostream>
#include <string>
std::string trimLeft(const std::string& input) {
if ((input.empty()) ||
((input.at(0) != ' ') && (input.at(0) != '\t'))) {
return input;
}
else {
size_t pos = 0;
for (size_t i = 0; i < input.length(); i++) {
if ((input.at(i) == ' ') || (input.at(i) == '\t'))
continue;
else {
pos = i;
break;
}
}
return input.substr(pos, (input.length() - pos));
}
}