Reputation: 117
In the program currently I wish to read in text from a text file line by line, extracting data from each line. Each line in the text file contains a letter such as “A” followed by a colon “:” followed by an integer such as “2”. The function in the program that should read in the data currently looks like this:
void readFile()
{
std::ifstream aFile;
std::string alldata;
std::string letter;
aFile.open("KeyPopularity.txt");
while (std::getline(aFile, alldata))
{
letter = alldata[0];
for (int i = 0; i < keyboardKeys.size(); i++)
{
if (keyboardKeys[i].character==letter)
{
keyboardKeys[i].noOfPresses = int(alldata[2]);
}
std::cout << letter << " ";
std::cout << int(alldata[2]) << "\n";
}
}
aFile.clear();
}
However the alldata variable at position 0 (alldata[0]) instead of listing just a single character ie the letter lists a number such as 87 before the letter eg. 87 W as opposed to just W. The question is why is this happening and is there a way to extract the data from each line in the text file line by line to obtain the letter at position 0 of a line string and the number at position 2 of the line string?
Upvotes: 0
Views: 49
Reputation: 29
Some observation/mistakes in your program:
You can rewrite your code like this:
void readFile()
{
std::ifstream aFile;
std::string alldata;
char letter;
aFile.open("KeyPopularity.txt");
while (std::getline(aFile, alldata))
{
letter = alldata[0];
for (int i = 0; i < keyboardKeys.size(); i++)
{
if (keyboardKeys[i].character == letter)
{
keyboardKeys[i].noOfPresses = alldata[2] - '0';
}
std::cout << letter << " ";
std::cout << alldata[2] - '0' << "\n";
}
}
aFile.clear();
}
Upvotes: 1