Need assistance with simple program (<10 lines)

Any ideas what's wrong with this? Although it compiles without a problem, I type in the first 10 digits of pi, press enter, and it won't work. I'm just doing this to get used to importing and exporting files. Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
using namespace std;

void main(){
	char pi[10];
	int pi_values[10];
	cin>>pi;
	for(int i=0;i!=10;i++){
		pi_values[i]=pi[i];
	}
	ofstream numbers;
	numbers.open ("Values of Pi.txt");
	numbers<<pi_values;
	numbers.close();
}
Last edited on
closed account (4Gb4jE8b)
well i'd be interested in what it does output. From what i'm seeing it would likely output "3"? If that is the case it's because of your use of char and int.

here's an example of something that would likely work better.

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <fstream>
using namespace std;

void main(){
	long double pi;
	cin>>pi;
	ofstream numbers;
	numbers.open ("Values of Pi.txt"); // less of a hassle to open, at least on windows
	numbers<<pi;
	numbers.close();
}


if you put in
3.141592653
you should get that out.
Last edited on
You need to convert each char to an int before assigning the var in line 10.
1
2
for(int i=0;i!=10;i++){
   pi_values[i]= (pi[i] - '0'); // Simple convert to int from char 

You need to cout out each element of pi_values to the file in a loop:
1
2
3
4
5
ofstream numbers;
numbers.open ("Values of Pi.txt");
for (int i = 0; i < 10; ++i)
   numbers<<pi_values[i]; // Like this.
numbers.close();


EDIT: If you enter a decimal ('.') you'll see an error with line ten. If you plan to enter it with the decimal stil use headlessgargoyle's example.
Last edited on
closed account (4Gb4jE8b)
unless of course you check if the char is a decimal, and have it skip that step if it is by doing something along the lines of

1
2
3
4
5
6
7
   for(int i=0;i!=10;i++)
   {
      if(pi[i] != '.')
      {
         pi_values[i]= (pi[i] - '0'); // Simple convert to int from char
      }
   }


mind you this is untested, so no guarantees
though it seems like it would break the loop upon finding the decimal, so that would have to be fixed
Last edited on
Topic archived. No new replies allowed.