Let's say I have the objects file1, file2, file3, ... up to file9.
I also have an array file_array[i] for i = 1 to 9 with a value assigned to each element.
How do I assign the array values to the corresponding objects with a for loop?
Let's say I have the objects file1, file2, file3, ... up to file9.
I also have an array file_array[i] for i = 1 to 9 with a value assigned to each element.
How do I assign the array values to the corresponding objects with a for loop?
Is that what you're asking?Code:string filename[6]; sprintf(filename, "file%d", file_array[i]);
Remember that arrays start at index 0, not 1. Also, the array isn't necessary is you're trying to accomplish what I laid out. You could simply use the loop iterator:
Code:for(i = 1;i <= 9;++i) sprintf(filename, "file%d", i);
If you understand what you're doing, you're not learning anything.
Sorry, but I don't think that's what I was referring to. The object names are file1, file2, etc. and I want to assign integer values to them, not to print the result.
No, it was what you were referring to! Go read the man page for sprintf, as it doesn't print anything.
As far as I can tell, what 843 is after is something like this:
Where ##file_array[i] means appending the number in file_array[i] to the variable name and assigning a value to it.Code:for (int i = 0; i < n; i++) object##file_array[i] = m;
If this is the case, a map might be a solution for you.
Also, I'd rather not use sprintf in C++. It's dangerous and unsafe.
I'd much rather recommend using string streams or alternatively Boost.Format.
Yes, but what's a 'map'?If this is the case, a map might be a solution for you.
I see, thanks!
Actually, I totally missed this was C++ and you were using strings, which makes my solution a bad one. As Elysia said, go for a stringstream. See this post for an example.