Hey guys! I'm new to this forum and also C++ programming(please bear with me) and just have a simple question. I recently did a test on how to remove commas off a string, to be more precise, my argument inputs in debugging and the answer was incorrect.
An example argument that I input into the debugging command was 1,345 and it came out as 13345. I was just wondering what went wrong and how could this be fixed or improved. Thanks!
P.S. I am trying to avoid using special functions/commands that could instantly remove them due to our school policy?
is saying copy the variable in the next element (i+1), into the 'current' element (i), if we are at a comma. This is why you see two lots of 3's in your output.
My C is rubbish, but maybe a good thing to do is create a new string, and each time you come across a character in your argv array that is NOT a comma, add it to this new string. So that at the end of your string iteration your 'new' string will contain all letters but not the comma.
As i said though, my knowledge about C-style arrays is pretty bad so that suggestion might not be great, but at least I pointed out why your code went wrong.
Do not use as in call the function. Do make use of the idea that is shown on the documentation. It is not even a trivial copy-paste, because there are unrelated, advanced concepts.
Notes on your current code:
* The stdafx.h is not used in the program and thus should not be included at all.
* There is no check for whether there actually is parameter argv[1].
I think mutexe's advice is really sound. In this instance it is much simpler to construct a comma-free string and copy in rather than move the characters around in-place. Perhaps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <cstring>
#include <iostream>
int main (int argc, char* argv[])
{
char *argString = argv[1]; // points to argv[1]
int argSize = strlen(argString); // size of original argument
char newString[argSize+1]; // new argument (big enough to hold old one)
int newChars = 0; // index of non-comma characters
for(int i=0; i < argSize; i++) // sort through argv[1]
if(argString[i] != ',') // if we dont have a comma...
newString[newChars++] = argString[i]; // copy character
newString[newChars] = 0; // end newString with null
strcpy(argString,newString); // copy newString to argv[1]
std::cout << argString;
}
Why create a separate string if you don't have to? The trick to problems like this is realizing that you need to keep track of where you're copying from and where you're copying to, separately: