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.
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 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;
}
(C++) I've created a function to open the text file and assign the contents to an array. The first 2 elements in the array are the size of the grid. However, if either or both of the first 2 numbers are double digits, it doesnt read them in as double digits. Is there any way of doing this?
int openMap()
{
std::string fileName;
std::cout << "Please enter the file name with extension that you want to open: ";
std::cin >> fileName;
system("CLS");
std::ifstream file(fileName); //OPENS MAP FILE
int tmp;
int i = 0;
if (!file.is_open()) //CHECKS IF THE MAP FILE HAS OPENED CORRECTLY
{
std::cout << "Error Occured!\nCould not open file.";
return 0;
}
while (!file.eof()) //READS THE MAP FILE AND PASSES THE INFORMATION INTO AN ARRAY
{
file >> tmp;
checkNumber(tmp);
if (valid == true) //IF THE CHARACTER IS NOT A NUMBER THEN IT WONT BE PASSED INTO THE ARRAY
{
tmpArray[i] = tmp;
i++;
valid = false;
}
row = tmpArray[1]; //ASSIGNS THE FIRST 2 NUMBERS OF THE MAP FILE TO ROW AND COL VARIABLES
col = tmpArray[0];
}
return row, col;
}
I would assume I have to rewrite
file >> tmp
in some sort of different way, but not sure how.
Is there a way to scan through the text file until it hits a whitespace?
The text file contents looks like this
6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0
(the 6 or 4 or both can be double digits instead)
Edit:
for (int j = 0; j < row; j++)
{
for (int k = 0; k < col; k++)
{
_map[j][k] = tmpArray[l];
std::cout << _map[j][k] << " ";
l++;
}
}
There's quite a number of bugs in the code, you should probably use a debugger to step through and identify which parts of your program don't behave as expected.
while(!file.eof())
file >> tmp;
checkNumber(tmp);
if (valid == true) //IF THE CHARACTER IS NOT A NUMBER THEN IT WONT BE PASSED INTO THE ARRAY
{
tmpArray[i] = tmp;
i++;
valid = false;
}
row = tmpArray[1]; //ASSIGNS THE FIRST 2 NUMBERS OF THE MAP FILE TO ROW AND COL VARIABLES
col = tmpArray[0];
You set row=tmpArray[1] and col = tmpArray[0] every iteration of the loop which is not only unnecessary but also incorrect, especially since row=tmpArray[1] is being executed at i=0 when nothing has been placed in tmpArray[1] yet.
EDIT: This is a lot smaller, less error prone due to less variables and type conversions, and easier to read:
int row,col;
//Add error checking here
cin >> col;
cin >> row;
cout << "Cols: " << col << " Rows: " << row << endl;
vector<vector<int> >_map(row, vector<int>(col,0));
for(int j=0; j < row; j++)
{
for(int k=0; k < col; k++)
{
int tmp;
cin >> tmp;
//Add error checking for tmp
_map[j][k] = tmp;
cout << _map[j][k] << endl;
}
}
There are some problems with your code. First the return type of your function is int but you are returning multiple values. Here is a complete running code which should solve your problem.
#include <iostream>
#include <fstream>
#include <vector>
std::vector< std::vector<int> > openMap() {
std::string fileName;
std::cout << "Please enter the file name with extension that you want to open: ";
std::cin >> fileName;
std::fstream myfile(fileName, std::ios_base::in);
int row, col;
myfile >> row;
myfile >> col;
int a;
std::vector< std::vector<int> > retval;
for (int i = 0; i < row; i++) {
std::vector<int> v1;
for (int j = 0; j < col; j++) {
myfile >> a;
v1.push_back(a);
}
retval.push_back(v1);
}
return retval;
}
int main(int argc, char * argv[])
{
std::vector< std::vector<int> > _map = openMap();
for(int i = 0; i < _map.size(); i++) {
for (int j = 0; j < _map[i].size(); j++) {
std::cout << _map[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
I guess that not so many people will be interested. But please see below a possible solution to your problem.
The code uses modern C++ algorithms.
It is very simple and straightforward.
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
int main() {
// Ask user, to give a filename
std::cout << "Please enter the file name with extension that you want to open: ";
// Get the filename from the user
if (std::string fileName; std::cin >> fileName) {
// Open the file and check, if it is open
if (std::ifstream sourceFile(fileName); sourceFile) {
// Read the number of rows and columns of the matrix
if (size_t numberOfColumns, numberOfRows; sourceFile >> numberOfColumns >> numberOfRows) {
// Create a matrix with the given number of rows and columns
std::vector<std::vector<int>> result(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Read data from the input stream and put it into the matrix
for (size_t i = 0; i < numberOfRows; ++i) {
std::copy_n(std::istream_iterator<int>(sourceFile), numberOfColumns, result[i].begin());
}
// Print result. Go through all lines and then copy line elements to std::cout
std::for_each(result.begin(), result.end(), [](std::vector<int>& c) {
std::copy(c.begin(), c.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n"; });
}
}
else {
std::cerr << "\n*** Error: Could not open source File\n\n";
}
}
return 0;
}
I'm working through a program where I have an input file containing state names, and three separate taxes for each state: sales tax, property tax, and income tax. I'm attempting to read the tax values (read as double variables) into an array of type double. Here is my code:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double a = 0,
b = 0,
c = 0;
double array[5][3];
string state_name;
ifstream fin;
fin.open("test.dat");
for (; fin >> state_name >> a >> b >> c;)
{
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 3; j++)
{
fin >> array[i][j];
cout << array[i][j] << "\t";
}
cout << endl;
}
}
return 0;
}
Here is the data file:
TEXAS .0825 .02 -.03
CALIFORNIA .065 .04 .05
MARYLAND .03 .025 .03
MAINE .095 .055 .045
OHIO .02 .015 .02
And from the this, the program outputs the array, except that each position reads -9.25596e+061. I was wondering if this was because the program was trying to read the string into the array. I was also wondering if there was a way to overlook the string in the file line by line so that only the double values are read into the array.
You read in the entire line in the for loop. You don't need to do fin >> array[i][j] later. Instead you should be doing this:
for (int i = 0; i < 5; i++)
{
fin >> state_name;
for(int j = 0; j < 3; ++j)
{
fin >> array[i][j];
cout << array[i][j] << '\t';
}
cout << endl;
if(!fin)
{
// handle an error reading the file
}
}
This should do the job:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
double array[5][3];
string state_name;
ifstream fin;
fin.open("test.dat");
// Read the file row by row
int row =0;
while(fin >> state_name >> array[row][0] >> array[row][1] >> array[row][2]) {
++row;
}
// Print the result
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 3; j++) {
cout << array[i][j] << "\t";
}
cout << endl;
}
return 0;
}
If you allow me to think one step further, you probably prefer to push each row into a vector rather than a static array. Otherwise you need to rewrite your code if the file will have more than 5 rows.
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;
}