Input errors

My program is having a hard time reading an input. Whenever I run the program, the output file becomes a mass of symbols, Can anyone please tell me what I'm doing wrong?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void read_stocks(char symbol[][SYMB_LEN], char name[][NAME_LEN], double price[])
{
	ifstream fin;
	ofstream fout;
	int temp;
	char holder[MAX];
	
	fin.open("stocks.dat");
	fout.open("out.txt");
	if (!fin)
	{
		cout << "Cannot open stocks.dat" << endl;
		exit(1);
	}
	temp = 0;
	//Stores Symbol in symbol array
	while (fin.getline(symbol[temp], SYMB_LEN))
	{
		//stores name in name array
		fin.getline(name[temp], NAME_LEN);
		//stores price in price array
		fin >> price[temp];
		temp++;
		fout << symbol[temp] << endl << name[temp] << endl << price[temp];
	}
	fin.close();
	fout.close();

}


Last edited on
Please post a small sample of your input file.

Why the C-strings instead of the safer std::string?

You are probably outputting uninitialized values to your output file, since you have changed the index value between the input and the output statements.

My input file is:
AAPL
Apple Computer
27
LU
Lucent Technologies
72
NSCP
Netscape
27.75
MOT
Motorola
49.5

The output I get is always:
ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌAAPL
-9.25596e+6

Also, for the C-strings, I'm using namespace std, since I'm still setting it up
What does "using namespace std;" have to do with using C-strings?


Did you read the last sentence in my last post? You are outputting uninitialized variables.

closed account (E0p9LyTq)
Using getline and the extraction operator (>>) together can cause problems. Either get all input via getline and convert numbers from strings, or skip any left-over whitespace with std::ws.

http://stackoverflow.com/questions/1744665/need-help-with-getline
http://en.cppreference.com/w/cpp/io/manip/ws

Using getline for all input, using a stringstream for safe conversions to numbers:
http://www.cplusplus.com/forum/articles/6046/#msg27163
Sorry, I misunderstood. I'm still new at this and I get everything mixed up.
Using the getline conversion worked. Thank you
Topic archived. No new replies allowed.