'How can I simplify these char array? [closed]
Hello I Have to loop this char array but the last argument changes by one everytime. The last number is supposed to be 100 and since i cant write 100 times the same line of argument i wanted to see if there is a simpler way of writing it
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
char command[100]= "ousbsim -r io PORTB 1";
char command2[100]= "ousbsim -r io PORTB 2";
char command3[100]= "ousbsim -r io PORTB 3";
char command4[100]= "ousbsim -r io PORTB 4";
char command5[100]= "ousbsim -r io PORTB 5";
char command6[100]= "ousbsim -r io PORTB 6";
and so on..
Solution 1:[1]
Simply create an array of strings, and then use a loop to populate the strings.
For example, try something like this:
#include <cstdio>
int main()
{
char commands[100][36];
for (int i = 0; i < 100; ++i)
{
std::sprintf(commands[i], "ousbsim -r io PORTB %d", i+1);
}
// use commands[0]..commands[99] as needed...
return 0;
}
Or, using C++'s std::string instead of C-style char[] arrays:
#include <string>
int main()
{
std::string commands[100];
for (int i = 0; i < 100; ++i)
{
commands[i] = "ousbsim -r io PORTB " + std::to_string(i+1);
/* alternatively:
#include <sstream>
std::ostringstream oss;
oss << "ousbsim -r io PORTB " << i+1;
commands[i] = oss.str();
*/
/* alternatively:
#include <format>
commands[i] = std::format("ousbsim -r io PORTB {}", i+1);
*/
}
// use commands[0]..commands[99] as needed...
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
