I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}
Related
I've been trying to import text from a .txt file into a 2D array of string, but it doesn't seem to be working. Each row in the .txt file has three values/elements separated that I need to copy.
This is the code:
// i am only allowed to use these libraries.
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
const int rows = 38;
const int columns = 3;
string companies[rows][columns];
// Inputting file contents
ifstream file;
file.open("companies.txt");
while(!file.eof())
{
for(int i = 0; i < 38; i++)
{
for(int j = 0; j < 3; j++)
{
getline(file, companies[i][j], ',');
}
}
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < 38; i++)
{
for(int j = 0; j < 3; j++)
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}
This is the data that I want to import :
Symbol,Company Name,Stock Price
ATRL,Attock Refinery Ltd.,171.54
AVN,Avanceon Ltd. Consolidated,78.1
BAHL,Bank AL-Habib Ltd.,54.97
CHCC,Cherat Cement Company Ltd.,126.26
One of the problems with your code is that you are only looking for , as a delimiter and not handling line breaks between the rows at all. Normally, I would suggest reading each row into a std::istringstream and then use std::getline(',') to parse each stream, but you say that you are not allowed to use <sstream>, so you will just have to parse each row manually using std::string::find() and std::string::substr() instead.
Also, using while(!file.eof()) is just plain wrong. Not just because it is the wrong way to use eof(), but also because your for loops are handling all of the data, so there is really nothing for the while loop to do.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
const int max_rows = 38;
const int max_columns = 3;
string companies[max_rows][max_columns];
string line;
string::size_type start, end;
// Inputting file contents
ifstream file("companies.txt");
int rows = 0;
while (rows < max_rows && getline(file, line))
{
start = 0;
for(int j = 0; j < max_columns; ++j)
{
end = line.find(',', start);
companies[rows][j] = line.substr(start, end-start);
start = end + 1;
}
++rows;
}
file.close();
cout << endl << endl;
// displaying file contents using for loop
for(int i = 0; i < rows; ++i)
{
for(int j = 0; j < max_columns; ++j)
{
cout << companies[i][j] << endl << endl;
}
}
cout << endl << endl;
return 0;
}
Online Demo
I am trying to create a program to combine two matrices. The first is to add them, the second is to subtract them, but I am getting an 1120 error. I don't know if that's because my code is bad, or if there's something wrong with my compiler. Here's what I've tried.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
fstream matrix_file("matricies.txt");
fstream result1_file("result1.txt");
fstream result2_file("result2.txt");
matrix_file.open("matricies.txt", ios::in);
if (!matrix_file) {
cout << "File was not opened!" << endl;
}
else {
cout << "File opened successfully!";
}
result1_file.open("result1.txt", ios::app);
if (!result_file) {
cout << "File was not created!" << endl;
}
else {
cout << "File created successfully!";
}
result2_file.open("result1.txt", ios::app);
if (!result_file) {
cout << "File was not created!" << endl;
}
else {
cout << "File created successfully!";
}
int matrix1[9];
int matrix2[9];
int result1Matrix[9];
int result2Matrix[9];
for (int i = 0; i < 9; ++i)
{
matrix_file >> matrix1[i];
}
for (int i = 0; i < 9; ++i) {
matrix_file >> matrix2[i];
}
for (int i = 0; i < 9; ++i) {
result1Matrix[i] = matrix1[i] + matrix2[i]
}
for (int i = 0; i < 9; ++i) {
result2Matrix[i] = matrix1[i] - matrix2[i]
}
for (int i = 0; i < 9; ++i) {
result1_file >> result1Matrix[i] ;
}
for (int i = 0; i < 9; ++i) {
result2_file >> result2Matrix[i];
}
matrix_file.close();
result1_file.close();
result2_file.close();
}
Line 35, 38: expected ';' in end line
Output file (result_file) must use operator '<<' instead of '>>'.
I am trying to create a maze map in txt file
here is the .txt file
7 7
e%
%% %%
%% %%%
%%% %%%
% %
% %
x % %%
7 and 7 are the number of rows and columns respectively. The spaces are the contents of the array too/
how can I print the spaces in c++
I have tried to code for it but it doesn't work with space:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
int rows = 0, cols = 0;
map >> rows >> cols;
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
map >> arr[i][j];
}
}
map.close();
cout << "This is the grid from file: " << endl;
for (int i = 0; i < rows; i++)
{
cout << "\t";
for (int j = 0; j < cols; j++)
{
cout << arr[i][j];
}
cout << endl;
}
system("pause");
return 0;
}
first time to ask question hope you guys can get the point thanks a lot for helping
map >> arr[i][j]; is a formatted input. It skips whitespaces. You have to use a different method, e.g. std::basic_istream<CharT,Traits>::get or std::basic_istream<CharT,Traits>::getline
Here is an example with get()
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
int rows = 0, cols = 0;
map >> rows >> cols;
// Skip linebreak after line: 7 7
map.ignore();
vector<vector<char> > arr(rows, vector<char>(cols));
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
// Read each char, also whitespaces and linebreaks
arr[i][j] = map.get();
}
// Skip linebreak
map.ignore();
}
map.close();
cout << "This is the grid from file: " << endl;
for (int i = 0; i < rows; i++)
{
cout << "\t";
for (int j = 0; j < cols; j++)
{
cout << arr[i][j];
}
cout << endl;
}
return 0;
}
I had to add two map.ignore(); because the line
map >> arr[i][j];
skipped all linebreaks but
arr[i][j] = map.get();
would read them so we have to manually skip them.
To better clarify my answer (as Yunnosch asked). My point wasn't to solve all problems, only to point at the problem of why the initial code does not work. True, I didn't clarify, I only posted some "new" code.
Original code posted by Cynthia doesn't work because operator>> reads all characters until the first space. My approach was to read the whole line and then break it to the same nested vector as in the initial code. Be aware that this also reads and stores "7 7" line as part of arr
Edit: I had to add a few semicolons for it to compile, and I removed 'reserve' since it can only confuse fresh programmers.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main()
{
ifstream map("m.txt");
if (!map) {
cout << endl << "Failed to open file";
return 1;
}
vector<vector<char> > arr;
string line;
// no need for size at start, we can deduce it from line size
while(getline(map, line))
{
vector<char> temp;
for (auto c : line)
temp.push_back(c);
arr.push_back(temp);
}
map.close();
cout << "This is the grid from file: " << endl;
// you can always get number of rows and cols from vector size
// additionally, each line can be of different size
for (int i = 0; i < arr.size(); i++)
{
cout << "\t";
for (int j = 0; j < arr.at(i).size(); j++)
{
cout << arr.at(i).at(j);
}
cout << endl;
}
system("pause");
return 0;
}
For example: [ticket.txt]
(Number) (Amount)
09 10
13 15
25 21
This is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int rowNumber = 0;
ifstream inFile, inFile2;
string line;
inFile.open("Ticket.txt"); //open File
inFile2.open("Ticket.txt");
if (inFile.fail()) // If file cannot open, the code will end
{
cout << "Fail to open the file" << endl;
return 1;
}
while (getline(inFile2, line)) // get whole lines and two valid numbers(numbers and amounts)
++rowNumber;
cout << "Number of lines in text file: " << rowNumber << "\n";
int myArray[rowNumber][2]; //declare 2d array
for(int i = 0; i < rowNumber; i++)
for(int j = 0; j < 2; j++)
inFile >> myArray[i][j];
}
My code is running well, but I want to convert a 2d array into vector. While reading file by arrays has a fixed size, so vector is a good solution to solve this problem.
Given your file structure you can read lines into a temporary vector and then insert it into a vector of vectors:
#include <iostream>
#include <fstream>
#include <vector>
int main(){
std::ifstream myfile("Tickets.txt");
std::vector<int> temprow(2);
std::vector<std::vector<int>> matrix{};
int rowcount = 0;
while (myfile >> temprow[0] >> temprow[1]){
matrix.push_back(temprow);
rowcount++;
}
for (int i = 0; i < rowcount; i++){
for (int j = 0; j < 2; j++){
std::cout << matrix[i][j] << ' ';
}
std::cout << std::endl;
}
}
This assumes your 2D array is N * 2.
So I've been working on a project for class and everything was going swimmingly, until I had to sort the information by last name in ascending order. To elaborate further, in my program I am supposed to take file input, apply it into whatever kind of variables I see fit, calculate their grades by comparing their answers against an answer key, and then sort the entries by last name. Without further ado here is my code! (be gentle)
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
const int TEST_SIZE = 10;
using namespace std;
struct StudentInfo
{
int id;
string fName;
string lName;
char testAnswers[10];
int totalPoints = 0;
int avg = 0;
char letterGrade;
};
void inputInfo(char[], StudentInfo[]);
void calcGrade(char[], StudentInfo[]);
void bubbleSort(StudentInfo[]);
void outputInfo(StudentInfo[]);
int main()
{
StudentInfo studentInfo[10];
string temp;
char answerKey[10];
inputInfo(answerKey, studentInfo);
calcGrade(answerKey, studentInfo);
bubbleSort(studentInfo);
outputInfo(studentInfo);
return 0;
}
void inputInfo(char answerKey[], StudentInfo studentInfo[])
{
cout << "Please enter the 10-question answer key: \n";
for(int i = 0; i < TEST_SIZE; i++)
{
cout << "Question " << i+1 << "\n";
cin >> answerKey[i];
}
ifstream inFile("student.txt");
for(int i = 0; i < TEST_SIZE; i++)
{
inFile >> studentInfo[i].id;
inFile >> studentInfo[i].fName;
inFile >> studentInfo[i].lName;
for(int j = 0; j < TEST_SIZE; j++){
inFile >> studentInfo[i].testAnswers[j];
}
}
}
void calcGrade(char answerKey[], StudentInfo studentInfo[])
{
for(int i = 0; i < TEST_SIZE; i++)
{
for(int j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[i].testAnswers[j] == answerKey[j])
{
studentInfo[i].totalPoints += 5;
}
studentInfo[i].avg = studentInfo[i].totalPoints * 2;
if(studentInfo[i].avg >= 90)
{
studentInfo[i].letterGrade = 'A';
}
else if(studentInfo[i].avg >= 80)
{
studentInfo[i].letterGrade = 'B';
}
else if(studentInfo[i].avg >= 70)
{
studentInfo[i].letterGrade = 'C';
}
else if(studentInfo[i].avg >= 60)
{
studentInfo[i].letterGrade = 'D';
}
else
{
studentInfo[i].letterGrade = 'F';
}
}
}
}
void bubbleSort(StudentInfo studentInfo[])
{
StudentInfo temp;
int i;
int j;
for(i = 0; i < (TEST_SIZE-1); i++)
{
for(j = 0; j < TEST_SIZE; j++)
{
if(studentInfo[j].lName < studentInfo[j-1].lName)
{
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
}
}
}
}
void outputInfo(StudentInfo studentInfo[])
{
cout << setprecision(1) << fixed;
cout << "Student ID\tStudent Name\tAnswers\tTotal Pts\tAverage\t Letter Grade" << endl;
for(int i = 0; i < TEST_SIZE; i++)
{
cout << studentInfo[i].id << "\t";
cout << studentInfo[i].lName << " ";
cout << studentInfo[i].fName << "\t";
for(int j = 0; j < TEST_SIZE; j++)
{
cout << studentInfo[i].testAnswers[j];
}
cout << "\t" << studentInfo[i].totalPoints << "\t";
cout << studentInfo[i].avg << "\t";
cout << studentInfo[i].letterGrade << "\n";
}
}
I've tried everything within my meager abilities, but my program always crashes. Assumedly during the bubble sort since it works fine without that section. If someone could enlighten me as to where I erred I would be very grateful. Sorry for any inconvenience that I've caused.
What happens here
temp = studentInfo[j];
studentInfo[j] = studentInfo[j-1];
studentInfo[j-1] = temp;
when j==0? You access out of bounds. You're better off using std::swap from <algorithm> like
std::swap(studentInfo[j], studentInfo[j+1]);
making sure that you run j until TEST_SIZE - 1. Or write the "manual" swap but with j exchanged by j+1.