0

If I want to write in for loop (for example) something with the next mention:

for(int i=0;i<5;i++) {
  char* str_3="atom_3";
  if(strcmp(str_3,"atom_i")!=0){  // I know that it's not true to get it by 
                                  //this line.  
     printf("FALSE");
  }
}

I want to get effect so that str_i will be compared with atom_0, atom_1 , ... , atom_4.
How can I do it?

Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69
AskMath
  • 415
  • 1
  • 4
  • 11
  • you have `str_3` but not `str_i` – RomanPerekhrest Apr 25 '18 at 15:06
  • @RomanPerekhrest I know, and I want that instead "atom_i" to get `atom_${i}` in according to the really value of `i` in any iteration.. – AskMath Apr 25 '18 at 15:07
  • I don't understand your question, what's the required output? – Tobi Apr 25 '18 at 15:11
  • @Tobi What that required is: how to do the next comparisons in singele line: `strcmp(str_3,"atom_0")` , `strcmp(str_3,"atom_1")` , `strcmp(str_3,"atom_2")` , `strcmp(str_3,"atom_3")` , `strcmp(str_3,"atom_4")` – AskMath Apr 25 '18 at 15:14
  • Are you asking how to convert the integer `i` to string and concatenate it with `atom_` ? Check this: [How to convert an int to string in C](https://stackoverflow.com/questions/8257714/how-to-convert-an-int-to-string-in-c) – Michal Lonski Apr 25 '18 at 15:18

1 Answers1

0

How can I write a string that changes from iteration to iteration?
... to get effect so that str_i will be compared with "atom_0", "atom_1" , ... , "atom_4".

Construct the compare string on each iteration.

// This is  not elegant, yet meets OP goals.
for(int i=0;i<5;i++) {
  char atom_i[30];
  sprintf(atom_i, "atom_%d", i);
  if(strcmp(str_i, atom_i)!=0){
     printf("FALSE");
  }
}

Yet a better approach would scan str_i and avoid iteration.

int d = 0;
char ch;  // Use to look for extra text
if (sscanf(str_i, "atom_%d%c", &d, &ch) == 1) {
  if (d >= 0 && d < 5) {
    ; // do something with str_i
  }
}
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256