Home c++ How to remove a char from its array

How to remove a char from its array




Hello everyone. There is such a task: In the Input file, a nickname is given, we need this nickname to be as low as possible in the table sorting by name, and only one character can be deleted. My code:

ifstream in ("input.txt");
ofstream out ("output.txt");
string str;
char ch [str.size ()], temp;
in & gt; & gt; str;
strcpy (ch, str.c_str ());
temp = ch [0];
for (int i = 0; i & lt; str.size (); i ++) {
if (ch [i] & gt; temp) {
delete ch [i];
else temp = ch [i];
string str2 = ch;
out & lt; & lt; str2;

We look, if the second character is lower in the alphabet of the first, we remove the first
The compiler points to one single error – delete ch [i];
Eroor: type ‘char’ argument given to ‘delete’, expected pointer
How to be?

Answer 1

delete from the wrong opera …

Your delete ch [i]; should be expanded to

for (int j = i + 1; ch [j-1] = ch [j]; ++ j );

Or use memmove () .

Answer 2

Listen, what are you doing here? Here you have a certain variable str, which, as can be inferred from the c_str () method, is of type std :: string. So why are you using a char array? Don’t get me wrong, I love C, but why use functions from cstring mixed with the string class? Moreover, you are not doing it right. And since you have a question with a C++ label, I recommend doing everything through string (and rightly so). Something like this:

ifstream in ("input.txt");
ofstream out ("output.txt");
std :: string str;
// here you generally took from str size, which is 0 at the moment
in & gt; & gt; str;
// two lines are not needed here at all - you have duplicate data
// further in the question, you indicated that you need to delete the first character if it is less than the second, but for some reason, go through the entire line, instead of doing this:
if (str [0] & lt; str [1])
 str.erase (str.begin ());
 str.erase (1);
out & lt; & lt; str;

Note that not only has the code been reduced, but the number of variables has also been reduced. Exactly to one.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions