Given a number, nr, I want to write many file names that include this number, and I would therefore like to know how to convert a number to a string for use in text file names. For example, say I had that nr=3000. If I want to write to a file called "testing_3000.txt", I would like to know how to do "testing_"+str(nr)+".txt". I know how to do this in python, but it seems tricky in C++. I have looked online but my implementation doesn't work. Any help would be appreciated.
I am using pointers to open a file and write to it, like this:
1 2 3 4
FILE *ofile;
ofile = fopen(mystring,"w");
if (ofile != NULL){
...
The dots represent that I am only showing the first relevant part. Anyway, I get an error message when I try your suggestion, of the following description:
214: error: cannot convert 'std::string' to 'const char*'for argument '1' to 'FILE* fopen(const char*, const char*)'
It doesn't seem to be accepting this 'mystring' which we constructed above. What may be the solution?
Also, on a slightly parallel note, my argv implementation does not work. I have the following two lines which construct an array with 5 values and then use argv[1] to decide which gets picked out depending on the command-line input to the executable file:
1 2
int nr_arr[]={3000,4000,5000,6000,7000};
int nr=nr_arr[argv[1]];
I am new to C++. Is the 'fopen' construction a C construction? Does it matter so much?
Yes. Only if you're concerned about type safety.
As you can see by the type of argv, it doesn't point to an integer type and an integer type is required for indexing an array. The compiler doesn't like it when you try to index an array with a pointer-to-char.
1 2 3 4 5
#include <cstdlib>
// ...
int nr=nr_arr[std::atoi(argv[1])];