Reading ints from .txt file to vector? - c++

For some reason I am getting zero values in my vector when I try to read from a txt file.
Here is my code:
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
while (read >> n){
source.push_back(n);
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}
The txt file is rather long but the format is:
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676

Here is reading one by one:
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
int main(){
ifstream read("e:\\problem13.txt");
vector<int> source;
char n;
while (read >> n){
source.push_back(n - '0');
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << endl << "Size: " << source.size() << endl << "Finished.";
}
But i recommend you reading line by line or if the file is no so big reading all in an std::string and process the string (reading from file is expensive).

In order to store each digit as an int, read each line and store it in a string. Then process each line.
int main(){
ifstream read("problem13.txt");
vector<int> source;
int n;
string line;
while (read >> line){
string::iterator iter = line.begin();
string::iterator end = line.end();
for ( ; iter != end; ++iter )
{
n = (*iter) - '0';
source.push_back(n);
}
}
for (int i = 0; i < source.size(); i++)
cout << source[i];
cout << "Finished.";
}

Related

How to convert 2D array into Vector

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.

Retrieve the first value from a map

I want to retrieve the first value of speed in from the typedef struct variable which I have added into the map. Right now my code is returning all the values from the CSV file which I have read. How do I get it to return only the first value to do a comparison to get the max value from the entire column?
I have tried using map.begin()->((*it).second).speed) but it does not work.
#include <iostream>
#include <fstream>
#include <string>
#include "Date.h"
#include "Time.h"
#include <stdlib.h>
#include <map>
using namespace std;
typedef struct
{
Time t;
float speed;
int solar;
}
WindLogType;
date d;
multimap<date, WindLogType> windlog;
ifstream input , csv;
ofstream output;
string filename;
int number,choice;
string *filelist = NULL;
WindLogType T1;
int main()
{
output.open("data/met_index.txt");
cout << "Enter number of file to read : " << endl;
cin >> number ;
for(int i =0; i< number ; i++)
{
cout << "Enter File name : " << endl;
cin >> filename;
output << filename << endl;
}
filelist = new string[number];
output.close();
input.open("data/met_index.txt", ios::in);
if(!input.is_open())
{
cout<< "File not found."<<endl;
return 0;
}
else
{
string line, line2;
while(getline(input, line, '\n'))
{
//cout << line << endl;
line = "data/" + line;
for(int i =0; i<number; i++)
{
filelist[i] = line;
cout << filelist[i];
csv.open(filelist[i].c_str());
string line,sDay, sMonth, sYear, sHH, sMM;
while(getline(csv,line2, '\n' ))
{
//cout << line2 << endl;
getline(csv, sDay,'/');
getline(csv, sMonth,'/');
getline(csv, sYear,' ');
getline(csv, sHH,':');
getline(csv, sMM,',');
int day1 = atoi(sDay.c_str());
int month1 = atoi(sMonth.c_str());
int year1 = atoi(sYear.c_str());
int hour1 = atoi(sHH.c_str());
int min1 = atoi(sMM.c_str());
float s1 = 0.0;
int sr = 0;
for (int i=0; i<10; i++)
{
csv >> s1;
csv.ignore(100, ',');
}
for(int j =0; j<18; j++)
{
csv >> sr;
csv.ignore(50,',');
}
T1.t.setTime(hour1, min1);
T1.speed = s1;
T1.solar = sr;
d.setDate(day1, month1, year1);
windlog.insert(pair<date, WindLogType>(d, T1));
multimap<date, WindLogType> :: iterator it;
for(it =windlog.begin(); it!= windlog.end(); ++it)
{
int max_value = ((*it).second).speed;
if((*it).second.speed > max_value){
max_value = ((*it).second).speed;
}
cout << max_value<<endl;
}
}
csv.close();
}
/**/
}
input.close();
input.clear();
//input.open(filelist[0].c_str(), ios::in);
}
return 0;
}
Your are printing max_value everytime.
Move the lines that find the maximum value after you've inserted everything, i.e., after the csv.close() for example. Also, do not print the maximum while searching for it but after you've iterated over all the elements.
multimap<date, WindLogType> :: iterator it =windlog.begin();
int max_value = ((*it).second).speed;
for(++it ; it!= windlog.end(); ++it)
{
if((*it).second.speed > max_value){
max_value = ((*it).second).speed;
}
}
cout << max_value<<endl;
Of course, be sure the map is not empty.
EDIT
WindLogType.speed is a float and you're using an integer when finding the maximum, it should be float too. Probably you already know it, but since C++11 you can use the auto specifier to let the compiler deduce automatically the correct type based on the assignment expression. It is available since Visual Studio 2010 and gcc 4.4 (for gcc you have to include the --std=c++11 option).
if (!windlog.empty()) {
auto it = windlog.begin(); // 'it' is an iterator
auto max_value = it->second.speed; // you're now sure it uses the same type
for(++it; it!= windlog.end(); ++it) {
max_value = std::max(it->second.speed, max_value);
}
std::cout << max_value << std::endl;
} else {
std::cout << "Empty map" << std::endl;
}

read int per line c++ error needs solution

hey guys I need help for my read code seems not working properly here's the code. The problem is as shown in the picture, the compiler are supposed to display all 1 million int value but it seems that my write or the display code was wrong. It shows nothing like it's not even reading.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <omp.h>
#include <ctime>
#include <cstdlib>
using namespace std;
int* CreateArray( int*);
void shellSortParallel( int*, int);
void shellSortSequential(int*, int);
void InsertSort( int*, int, int, int);
int main()
{
int array_size = 1000000;
int n=0;
int* arr=new int[array_size];
ifstream fin("OUTPUT1.txt");
if(! fin)
{
cout << "File could not be opened." << endl;
}
else
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
}
fin.close();
int length = 1000000;
double endTime = 0, startTime = 0, totalTime = 0;
double start, end;
cout << "Program is now sorting using shell sort" <<endl;
startTime = time(NULL);
start = omp_get_wtime();// Start performance timer 1 run
shellSortParallel(arr, length);//Run the algorithm
end = omp_get_wtime();// End performance timer 1 run
endTime = time(NULL);
totalTime = endTime - startTime;
cout << "This is the time it took to run. " << totalTime << endl;// time in seconds
int stupid = 0;
cin >> stupid;
cout << "Program has completed all tasks!!" << endl;
return 0;
}
void shellSortParallel(int array[], int length)
{
int h;
int j = 0;
int temp = 0;
int i = 0;
for(h =length/2; h > 0; h = h/2)
{
#pragma omp parallel for shared( array, length, h, i) default(none)
for( i = 0; i < h; i++)
{
//int ID = omp_get_thread_num();
InsertSort(array, i, length, h);
}
}
}
void InsertSort(int arr[], int i, int length, int half)
{
//cout << ID << " ";
int temp = 0;
int j = 0;
for (int f = half + i; f < length; f = f + half)
{
j = f;
while(j > i && arr[j-half] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-half];
arr[j-half] = temp;
j = j -half;
}
}
}
and here is the short version of the file that I'm going to read. Its a random number between 1 to 1million per line
2377763
88764877846
281327
60
625
86
646127818
14551
2177645
32033
1826761
555173
3415445377
32430
1101
any help would be much appreciate, thank you before
By if(fin>>data) you are not just testing, but retrieving data from stream. I suggest use ifs.good() for testing. Overall, you can write such a code instead
std::ifstream fin ("OUTPUT1.txt", std::ifstream::in);
char c = fin.get();
while (fin.good())
{
std::cout << c;
c = fin.get();
}
arr[n-1] = '\0'; is not correct because it's not an array of character so don't mind.
to correct it:
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
why allocating such huge array of integers? use vector is a good thing:
vector<int> vec;
ifstream fin("OUTPUT1.txt");
int data;
while(fin >> data)
{
vec.push_back(data);
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
fin.close();
88764877846 out band of an integer which causes the loop stop reading so you have to either get values as strings then convert into __int64 or __int128
to read values as strings:
string sLine;
int nLines = 0;
ifstream fin("OUTPUT1.txt");
// first read to get number of lines
while(getline(fin, sLine))
nLines++;
//create an array of strings
string* pstrValues = new string[nLines];
// set the get pointer to the beginning of file because the previous read moved it
fin.clear();
fin.seekg(0, ios::beg);
int i = 0;
while(getline(fin, sLine))
{
pstrValues[i] = sLine;
i++;
}
cout << "Displaying Array..." << endl << endl;
for( i = 0; i < nLines; i++)
cout << pstrValues[i] << endl;
fin.close();
now you have an array of strings convert it to int values but you must convert to __int64 because as I said there are values bigger than size of int (4bytes)

How to read a 2d array from a file without knowing its length in C++?

Like the title says I'm trying to read an unknown number of integers from a file and place them in a 2d array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream f;int i,j,n,a[20][20];char ch;
i=0;j=0;n=0;
f.open("array.txt", ios::in);
while(!f.eof())
{
i++;
n++;
do
{
f>>a[i][j];
j++;
f>>ch;
}
while(ch!='\n');
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<endl;
cout<<endl;
}
return 0;
}
and my "array.txt" file :
1 1 1
2 2 2
3 3 3
After compiling the program, it prints this
As your input file is line oriented, you should use getline (C++ equivalent or C fgets) to read a line, then an istringstream to parse the line into integers. And as you do not know a priori the size, you should use vectors, and consistently control that all lines have same size, and that the number of lines is the same as the number of columns.
Last but not least, you should test eof immediately after a read and not on beginning of loop.
Code becomes:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{
fstream f;
int i=0, j=0, n=0;
string line;
vector<vector<int>> a;
f.open("array.txt", ios::in);
for(;;)
{
std::getline(f, line);
if (! f) break; // test eof after read
a.push_back(vector<int>());
std::istringstream fline(line);
j = 0;
for(;;) {
int val;
fline >> val;
if (!fline) break;
a[i].push_back(val);
j++;
}
i++;
if (n == 0) n = j;
else if (n != j) {
cerr << "Error line " << i << " - " << j << " values instead of " << n << endl;
}
}
if (i != n) {
cerr << "Error " << i << " lines instead of " << n << endl;
}
for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) {
for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
cout << " " << *jt;
}
cout << endl;
}
return 0;
}
You may want to look into using a vector so you can have a dynamic array.
Try:
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
fstream f;
int i, j, n, a[20][20];
string buf;
i = 0;
j = 0;
n = 0;
f.open("array.txt", ios::in);
while (1) {
getline(f, buf);
if (f.eof()) break;
stringstream buf_stream(buf);
j = 0;
do {
buf_stream >> a[i][j];
j++;
} while (!buf_stream.eof());
i++;
n++;
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Also, if you really want to read arbitrarily large arrays, then you should use std::vector or some such other container, not raw arrays.

Why am i getting this out put?

I've been working on this program for a very long time now and I think I'm close to being done. However, my code is outputting something strange and I cannot find the issue.
Expected output:
This is a happy tESt to check if my reader works!
An happy alligator was AT tHe happy park and a happy a cow blew its nose in a happy scarf. are you an happy Octagon THe
Actual output:
This is a tE happySt to check if my reader works!
a happy
THe Happy
How can I make the following code behave as I expect?
#include <iostream>
#include <string>
#include <cctype>
#include <fstream>
#include <sstream>
#include <locale>
using namespace std;
void
usage(char *progname, string msg){
cerr << "Error: " << msg << endl;
cerr << "Usage is: " << progname << " [filename]" << endl;
cerr << " specifying filename reads from that file; no filename reads standard input" << endl;
}
string capitalization(string word,string adj){
for(int i = 0; i <= word.length(); i++){
if(isupper(word[i])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = toupper(adj[j]);
return adj;
}
}
else if(isupper(word[0])){
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
else{
for(int j = 0; j <= adj.length(); j++){
adj[j] = tolower(adj[j]);
return adj;
}
}
}
}
int main(int argc, char *argv[]){
string adj;
string file;
cin >> adj;
cin >> file;
string line;
string articles[14] = {"a","A","an","aN","An","AN","the","The","tHe","thE","THe","tHE","ThE","THE"};
ifstream rfile;
rfile.open(file.c_str());
if(rfile.fail()){
cerr << "Error while attempting to open the file." << endl;
return 0;
}
string::size_type pos;
string word;
string words[1024];
while(getline(rfile,line)){
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
words[i] = word;
for(int j = 0; j <= 14; j++){
if(word == articles[j]){
string article = word;
iss >> word;
pos = line.find(article);
//cout << pos << endl;
string adjec = capitalization(word,adj);
int position = (pos + word.length());
line.insert(position, " " + adjec);
continue;
}
}
}
cout << line << "\n";
}
}
This may not fix any of your problems, but...
The logic in these lines is wrong.
istringstream iss(line);
for(int i = 0; i <= line.length(); i++){
iss >> word;
Let's say your line is
This is a test.
For this line, line.length() is 15 but there aren't 15 words. What you need is
istringstream iss(line);
while ( iss >> word ) {