.txt file into 2D Char* Array - c++

I'm fairly new to C++ and I'm working on point of sale program from a class in which I will need to read in the menu option along with the price. I'm attempting to read in a .txt file into a 2D Char* but I keep on getting the error message
Thread 1: EXC_BAD_ACCESS (code=1, address=0x0)
from line containing
inFile >> array[i][j];
I'm assuming this error is arising due to the way that I'm trying to assign values to each element in the array. I'm sure how to accomplish it.
// Main function
int main (){
char *array[4][3];
string fileName;
vector<string>order;
fileName = fileLoc();
getMenu(fileName, array);
return 0;
}
string fileLoc(){
string file;
cout << "Enter file name or location: ";
cin >> file;
return file;
}
void getMenu(string fileName, char *array[][3]){
ifstream inFile(fileName.c_str());
if (!inFile){
cout << "File failed to open\n";
}
for (int i = 0; i < 4; ++i){
for (int j = 0; j < 3; ++j){
inFile >> array[i][j];
cout << array[i][j] << endl;
}
}
inFile.close();
}
The .txt file I am reading from looks like such
B Burger 3
S Soda 1
F Fries 2
C Chips 1.5

Related

Parse (split) a txt file with a string and int in c++

im a Student and new to this site. I want to split my txt file with my highscore data back to my Highscore List.
The txt file stores my Highscore like name:score
My parsing is not working and i dont know why?
I just want to split it to name and score again and then put it in my HighscoreList.
If you have any question about the code just ask :)
#include "highscore.h"
highscore::highscore(){
}
struct highscore::Player{
string spielerName;
int score;
};
void highscore::writeHighscore(string name, int score ,int playerNumberx){
Player HighscoreListe[100];
for(int i=0;i<=99;i++){
HighscoreListe[i].score = {0};
}
for(int i=0;i<=99;i++){
HighscoreListe[i].spielerName = "leer";
}
HighscoreListe[playerNumberx].spielerName = name;
HighscoreListe[playerNumberx].score = score;
int i, j,temp;
string temp1;
ifstream myfile("scores.txt");
string line;
//heres the point where i need help!!
if (myfile.is_open()){
int z=0;
while(getline(myfile, line)){
string name1;
string score1;
int d = 20;
while(line[z] != ':'){
name1 += line[z];
z++;
}
z = z+2;
while(line[z] != '\0'){
score1 += line[z];
z++;
}
HighscoreListe[d].spielerName = name;
HighscoreListe[d].score = score;
d++;
}
myfile.close();
}else cout << "Unable to open file" << endl;
for(i = 0; i<100; i++) {
for(j = i+1; j<100; j++)
{
if(HighscoreListe[j].score < HighscoreListe[i].score) {
temp = HighscoreListe[i].score;
temp1 = HighscoreListe[i].spielerName;
HighscoreListe[i].score = HighscoreListe[j].score;
HighscoreListe[i].spielerName = HighscoreListe[j].spielerName;
HighscoreListe[j].score = temp;
HighscoreListe[j].spielerName = temp1;
}
}
}
ofstream myfilex("scores.txt");
if (myfilex.is_open()){
for(int i = 99;i>89;i--){
myfilex << HighscoreListe[i].spielerName << ":" << HighscoreListe[i].score<<endl;
}
myfilex.close();
}
else cout << "Unable to open file" << endl;
}
void highscore::readHighscore(){
string line;
ifstream myfile("scores.txt");
if (myfile.is_open()){
while(getline(myfile, line)){
cout << line << endl;
}
}
else cout << "Unable to open file" << endl;
}
Make a >> overload for highscore::Player.
In the >> overload
Use std::getline to read a line from the input stream.
Create a std::istringstream out of the line.
Use std::getline to read up to the : from the istringstream into a local string name;.
Use another std::getline to read the rest of the line into a string.
Convert the string into an int with std::stoi and store into a local int score;. Make sure you provide a pos argument.
Ensure that the entire string was converted by comparting the pos argument with the string's length.
If nothing went wrong, store name and score into the highscore::Player passed by the caller. Otherwise, set the failbit on the input stream with setstate
return the input stream.
Now the reading code should be something simple like
int scorecount = 0;
while (myfile >> HighscoreListe[scorecount])
{
scorecount++;
}

Text from file not reading into arrays

This portion of my program is intended to read in a list of names and grades of students, then average them together and display them.
I declared a function as such:
int loadStudentNamesGrades(string students[], int grades[][MAX_GRADES],
string fileName, int maxStudents);
Here is the Definition:
int loadStudentNamesGrades(string students[],
int grades[][MAX_GRADES],
string fileName,
int maxStudents)
{
ifstream inFile; // input file stream
string nameFile; // name of file
string studentName; // name of student
int numStudents = 0; // number of students initialized to 0
inFile.open(fileName); // open the file
if (!inFile)
{
cout << "Unable to Open File!\n";
system("PAUSE");
exit (EXIT_FAILURE);
}
for (int i = 0; i < maxStudents && (inFile >> studentName >> numStudents);
i++, numStudents++)
{
for (int j = 0; j < MAX_GRADES; j++)
{
inFile >> grades[i][j];
}
students[i] = studentName;
}
inFile.close();
return numStudents;
}
When I try to run my program, my menu displays but none of the values from the text file populate. As far as I know my file is opening properly because it does not return an error.
It looks like it reads into the arrays, but you are not returning those. Try passing your arrays by reference, something like this:
int loadStudentNamesGrades(string (&students)[10], int (&grades)[10][MAX_GRADES],
string fileName, int maxStudents)
You could also think about using vectors instead of arrays.

Getting input from a file C++ (Matrix Array Input)

I will have user input a file which will contain some data like this :
numRows
numCols
x x x ... x
x x x ... x
.
..
...
Now I am having trouble reading data from a file like this. I am not understanding what should I do to read each integer from each line. This is what I have so far:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class my_exception : public std::exception {
virtual const char *what() const throw() {
return "Exception occurred!!";
}
};
int main() {
cout << "Enter the directory of the file: " << endl;
string path;
cin >> path;
ifstream infile;
cout << "You entered: " << path << endl;
infile.open(path.c_str());
string x;
try
{
if (infile.fail()) {
throw my_exception();
}
string line;
while (!infile.eof())
{
getline(infile, line);
cout << line << endl;
}
}
catch (const exception& e)
{
cout << e.what() << endl;
}
system("pause");
return 0;
}
Also what I want is to store data at each line! That means after the first line I want to store data into the corresponding variable and each cell value.
I am confused as to how can I get each integer and store them in a unique(numRows and numCols) variable?
I want to save first two lines of the file into numRows and numCols respectively, then after each line's each integer will be a cell value of the matrix. Sample input :
2
2
1 2
3 4
TIA
Try this out. The first line reads in the path. Then, using freopen we associate the file provided with stdin. So now we can directly use cin operations as if we are directly reading from stdin and as if the input from the file is typed line for line into the console.
Following this, I create two variables corresponding to numRows and numCols and create a matrix of this dimension. Then I create a nested for loop to read in each value of the matrix.
string path;
cin >> path;
freopen(path.c_str(),"r",stdin);
int numRows, numCols;
cin >> numRows >> numCols;
int matrix[numRows][numCols];
for(int i = 0; i < numRows; i++){
for(int j = 0; j < numCols; j++){
cin >> matrix[i][j];
}
}
Alternatively you can use this to create your matrix
int** matrix = new int*[numRows];
for(int i = 0; i < numRows; i++)
matrix[i] = new int[numCols];
See this for more reference.

How to read a table from .txt file to C++

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly.
Here is the code:
#define I 5
#define J 5
#define P 2
int i,j,k; //for loops
int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];
inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}
for(i=0; i<I; i++)
for(j=0; j<J; j++)
inFile >> C[i][j];
outFile.open("results.txt");
outFile<< "C" <<endl;
for(i=0;i<I;i++)
{
for(j=0;j<J;j++)
outFile<< C[i][j];
outFile<< endl;
}
inFile.close();
outFile.close();
return 0;
}
C is a matrix of integer values 2 3 5... but what I get is
316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
You should output a whitespace after each number, otherwise they will be all glued together.
outFile<< C[i][j] << " ";
You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).
I suspect that you are having problems with new lines, below modification will ignore new line character after reading each line:
for(i=0; i<I; i++) {
for(j=0; j<J; j++)
inFile >> C[i][j];
inFile.ignore(); /// <<<--------
}
It seems you are writing uninitialized variables to your output file, leading to undefined behavior.
I suspect your C.txt file does not contain the 5x5 matrix your program is looking for.
You should add a simple error check, e.g.:
for(i=0; i<I; i++)
for(j=0; j<J; j++)
if (!(inFile >> C[i][j])) { /* something's wrong here */ }

Read file from txt

I ve got a txt file with double matrix 50x8. The first two lines contains the array size
50
8
the 50x8 matrix. When i trid to read this file with the above code:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("C:/Users/zenitis/Desktop/BTHAI_2.3b-src/BTHAI/txtFiles/W1.txt");
double events[50][8];
while (!infile.eof())
{
for(int j=0;j<50;j++)
{
for(int k=0; k<8;k++)
{
infile >> events[j][k];
// infile.get(c
}
}
} //end while
infile.close();
for(int i = 0; i<50; i++){
for(int l=0; l<8; l++){
cout << events[i][l] << " ";
}
cout << "\n";
}
cout << events[0][0];
system("pause");
return 0;
}
Firstly when i print the results the first two elements of the events matrix are the last two of the file. Secondly any idea how to read just the two first elements which is in fact the size of the matrix????
You read the number of rows and columns like this:
int R, C;
infile >> R;
infile >> C;
You do it before the nested loops that read the rest of the file. Then you use the numbers from the file as your end-of-loop targets, rather than hard-coding 50 and 8.