I am having an issue reading in lines from a file, converting each into a string, then splitting that string into components (Int, string, double), and then printing them out. It works fine up until element number 10, and then doesn't print correctly and I have no idea why. Please Help!
#pragma once
#include <stdio.h>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <sstream>
usingnamespace std;
//reads in the table prototype
void read_in_table(string line_input);
int main()
{
string line_input; //String for lines of text
string path = "PeriodicTableElements.txt";//text file for elements
ifstream input;//create stream
input.open(path);//open stream
if (input.fail())//run if fail to open file
{
cerr << "Could not open input file." << endl;
system("PAUSE");
exit(0);
}
while (input.peek() != EOF)//while file is open
{
getline(input, line_input, '\n');
read_in_table(line_input);
}
input.close();//close stream
cout << endl;//blank line
system("PAUSE");
return EXIT_SUCCESS;
}
//read in data to table
void read_in_table(string line_input)
{
double weight;
int i = 0;
int j = 0;
int k = 0;
while (line_input[i] != ' ')
{
++i;
if (line_input[i] = ' ')
{
j = i+1;
k = j;
while (line_input[k] != ' ')
{
k++;
}
}
}
int element_number = stoi(line_input.substr(0, i));
string element = line_input.substr(j, k);
int weight_length = line_input.size();
string weight_string = line_input.substr(k, weight_length);
istringstream convert(weight_string);
if (!(convert >> weight))
weight = 0;
cout << "Element " << element << " " << "Weight " << weight << " " << "Number " << element_number << endl;
}
And here is the file:
>PeriodicTableElements.txt
(number, element, weight format)
1 H 1.008
2 He 4.0026
3 Li 6.94
4 Be 9.0122
5 B 10.81
6 C 12.011
7 N 14.007
8 O 15.999
9 F 18.998
10 Ne 20.180
11 Na 22.990
12 Mg 24.305
13 Al 26.982
14 Si 28.085
15 P 30.974
100 Fm 257.10
101 Md 258.10
102 No 259.10
103 Lr 262.11
104 Rf 265.12
105 Db 268.13
Eventually I will be transferring the information to a hash table, I'm just verifying that it can be read in and parse correctly. The actual text file is much larger. The issue I seem to be having is correctly splitting the line into the components I need, could you explain "//use your vars"?
Well i depends what you want to do with them.
A good idea is first to print them to see if they are read properly. cout << number << '\t' << element << '\t' << weight_format << '\n';
Eventually I will be transferring the information to a hash table
Might be a good idea to put them in a struct or class first and then use one of the set classes the STL provides - which uses a hashtable internally.
At the moment, I am just ensuring that the lines are split correctly and printing that to test the split. Here is the read_in_table function as I currently have it to read data into the hash table: