0

I am trying to change the extension of a file from '.xxx' to '.err' (xxx is whatever). Here is my code:

for (size_t i=0; i<strlen(m_sMFLfile); i++) {
  errorfile[i] = m_sMFLfile[i];
  if(m_sMFLfile[i] == '.') {
    errorfile[i,i+3] = ".err";
    break;
    }
 }

However, I get: error C2440: '=': cannot convert from 'const char [5]' to 'char' errorfile is defined as:

char          errorfile[256];

Can't seem to answer this post for some reason, but here is what I understand I need to do:

for (size_t i=0; i<strlen(m_sMFLfile); i++) {
  errorfile[i] = m_sMFLfile[i];
  if(m_sMFLfile[i] == '.') {
    errorfile[i+1] = 'e';
    errorfile[i+2] = 'r';
    errorfile[i+3] = 'r';
    break;
    }
  }

Gawd help me if it is 1000 chars long...

Adrian
  • 267
  • 2
  • 9
  • 2 problems with this line `errorfile[i,i+3] = '.err';` (1) `[i,i+3]` you can't use array indexing to create a range, (2) the quote `'` is used for single characters. – Richard Critten Mar 26 '23 at 18:41
  • Note that `'.err'` is an `int` literal, not a string literal. There are also several other severe issues with your code. In particular the expressions `i,i+3` (comma operator) and `m_sMFLfile[i] == '.'` (a pointer comparison) definitely do not do what you think they do. – Brian61354270 Mar 26 '23 at 18:42
  • @RichardCritten I changed ' to ", but I still get error C2440: '=': cannot convert from 'const char [5]' to 'char' – Adrian Mar 26 '23 at 18:46
  • @Adrian `errorfile[i,i+3]` does not do what you want you need to use a loop and copy the characters 1 at a time. To be technical the part `errorfile[i,i+3]` evaluates `i` and throws away the result, then evaluates `i+3` and uses the result to index the array. See [Built-in comma operator](https://en.cppreference.com/w/cpp/language/operator_other#Built-in_comma_operator) – Richard Critten Mar 26 '23 at 18:48
  • @RichardCritten like : errorfile[i] = "."; errorfile[i+1] = "e"; errorfile[i+2] = "r"; errorfile[i+3] = "r"; – Adrian Mar 26 '23 at 18:50
  • Given what you're doing, you might find this interesting: https://stackoverflow.com/a/1580014/179910 (though it may not lead to a practical solution for you). – Jerry Coffin Mar 26 '23 at 19:09
  • Instead of a char array, you could perhaps use `filesystem::path` to store the filename. As it happens, it has a [replace_extension](https://en.cppreference.com/w/cpp/filesystem/path/replace_extension) member that does all the work. – BoP Mar 26 '23 at 19:31

0 Answers0