C++ Code
The C++ version of your code runs, but there is room for improvements:
- You call your output stream fis (file input stream). This is confusing. Call it file, or output stream or something that reflects on the true nature of the variable.
- The instructions said separate your number by space, but you used new line instead.
- using namespace could make your code shorter, but it could also pollute namespaces, so it's a good practice (especially in larger code bases) that you instead fully qualify the name of your functions.
C Code
You had some compilation issues here and general logic problems.
- You should check the documentation on how to use the printf() function.
- You never wrote to a file, instead tried to open the file multiple times over and over in the loop.
- There's no need to include the string.h header.
General Comments
- It is generally a good idea to tell the user what s/he's supposed to do (e.g. print the instruction before reading the input).
- Also a good idea, if one checks if the file was successfully opened before you start reading/writing it.
- In OnlineGDB writing to an output could be tricky. Some file names cannot be used for some reason (system reserved files perhaps). One of them would be "data.out". Instead, as you did, a different file name could be used when the code is run on OnlineGDB.
- For the above reason, I added a const char * fileName to both solutions so the file name can easily be replaced if needed.
The Solutions
Here's the enhance C++ solution:
#include <fstream>
#include <iostream>
int main()
{
const char * fileName = "file.out";
std::cout << "Please, enter a number: ";
unsigned long n;
std::cin >> n;
std::ofstream file(fileName); // I declare the file and open it for data writing
if (!file.is_open())
{
std::cout << "Could not open file: " << fileName << std::endl;
return -1;
}
while (n != 0)
{
file << n << ' '; // Write the number in the file,
n /= 10; // then delete the last digit
}
file.close();
return 0;
}
Here's the enhanced C solution:
#include <stdio.h>
int main()
{
const char * fileName = "file2.out";
printf("Please, enter a number: ");
int n;
scanf("%d", &n);
FILE * f = fopen(fileName, "w");
if (!f)
{
printf("Could not open file: %s\n", fileName);
return -1;
}
while (n != 0)
{
fprintf(f, "%d ", n);
n /= 10;
}
fclose(f);
return 0;
}