(c++) trying to read numbers into array, getting junk numbers on output - c++

I've searched and searched this topic and still nothing so I'm resorting to this.
NOTE: Can't use vectors at all
So I'm trying to open up a text file in this program and read the numbers into an array. The program opens it up, and reads them (I'm assuming), but when I read the numbers the back, they are junk numbers. Not really sure where it went wrong, would appreciate some help. Here's my code:
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void readNumbers(int numbers[]);
const int MAX_SIZE = 12;
int main()
{
int numbers[MAX_SIZE];
readNumbers(numbers);
for (int i = 0; i < MAX_SIZE; i++)
{
cout << numbers[i] << endl;
}
return 0;
}
void readNumbers(int numbers[])
{
int num = 0;
ifstream inFile;
inFile.open("numbers.txt");
if (!inFile)
{
cout << "Cannot open the file" << endl;
}
else
{
inFile >> num;
while(inFile)
{
int i = 0;
numbers[i] += num;
i++;
inFile >> num;
}
}
inFile.close();
}
Output:
1606416400
32767
0
0
0
0
0
0
0
0
0
0

The i variable is local to the loop. Try moving it outside:
int i = 0;
while(inFile)
{
numbers[i] += num;
i++;
inFile >> num;
}

Your array numbers[] is not initialized and you are incrementing nothing but garbage values numbers[i] += num;
hence it prints junk numbers.
If incrementing is important use:
int numbers[MAX_SIZE]={0} //while declaration
If not:
numbers[i]=num //inside while
Also int i=0 should be outside while as i will always be 0 inside while.

You're not initializing your numbers array, so it'll have garbage in it. Why are you using += when storing num in numbers[i]? Shouldn't you be using an assignment there?
numbers[i] = num;
(And also, as previously mentioned, the i index needs to be declared outside the loop, otherwise you're always adding/assigning to the first element in numbers.)

fixed few errors in usage of array.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void readNumbers(std::string* numbers);
const int MAX_SIZE = 12;
int nSize = 0;
int main()
{
std::string numbers[MAX_SIZE];
readNumbers(numbers);
for (int i = 0; i < nSize; i++)
{
cout << numbers[i] << endl;
}
return 0;
}
void readNumbers(std::string* numbers)
{
ifstream inFile;
inFile.open("numbers.txt");
if (!inFile)
{
cout << "Cannot open the file" << endl;
}
else
{
while(!inFile.eof())
{
char temp[100] = {0};
inFile.getline(temp, 100);
numbers[nSize++].assign(temp);
if (nSize == MAX_SIZE) break;
}
}
inFile.close();
}

Related

Is there a way i can use a text file to operate a program to display the occurrence of numbers in C++?

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream ticket ("numbers.txt");
bool isCovered[99];
int number;
for (int i = 0; i < 99; i++)
isCovered[number] = false;
// Read each number and mark its corresponding element covered
ticket >> number;
while (number != 0)
{
isCovered[number - 1] = true;
ticket >> number;
}
// Check if all covered
bool allCovered = true; // Assumes all covered initially
for (int i = 0; i < 99; i++)
if (!isCovered[i])
{
allCovered = false; //Finds one number not covered
break;
}
return 0;
I know i may have confused you all with the last question i posted but this time i understand the concepts and have an even better question. How can i display the number of occurrences using a txt file in fstream while using C++? And how would i properly use my for and if loops for said problem, thanks?
Update: Got the numbers from the text file to display as well as numbers 1 - 99. But how do i code for the number of occurrences?
#include <fstream>
#include <string>
using namespace std;
int main()
{
int i;
// Open the text file in the system
ifstream infile;
infile.open("numbers.txt");
if(infile.fail())
{
cout << "This file does not work";
}
else{
string s;
while(infile >> s){
cout << s << endl;
}
}
// Display all numbers 1 through 99
for (i = 1; i < 99; i++){
cout << i << endl;
}
}

Creating array after getting variable in other function

A text file looks like this:
3
String
String2
String3
I must create a function to read all the strings from text file, save them to array and then display it in main function. For example
void reading(int & count, string strings[]) {
ifstream fd "text.txt";
fd >> count;
for (int i=0; i<count; i++)
fd >> strings[i];
fd.close();
And main function:
int main() {
int count=0;
string strings[100];
reading(count, strings);
for (int i=0; i<count; i++)
cout << strings[i] << endl;
The number of strings is written in first line of text file. How can I create an array of exactly that number? I need it to be able to access it in main/other functions. (For example function for writing into another text file).
In case there is a super important reason to do that with an array, then use std::new, like this:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int reading(string** str_array, int& size, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int n = 0;
infile >> size;
try{
*str_array = new string[size];
string str;
for (; n < size && infile; ++n) {
infile >> str;
(*str_array)[n] = str;
}
if (n != size)
cerr << "ERROR, read less than " << size << " strings!!\n\n";
} catch(bad_alloc& exc) {
return -2;
}
return 0;
}
int main() {
string* str_array = NULL;
int size;
if(reading(&str_array, size, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(int i = 0; i < size; ++i)
cout << str_array[i] << endl;
delete [] str_array; // DO NOT FORGET TO FREE YOUR MEMORY
str_array = NULL;
return 0;
}
Output:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
However, you are in c++ and you are not using an std::vector for this?
Look how simple it is with that:
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int reading(vector<string>& v, string filename) {
ifstream infile(filename.c_str());
if(!infile) {
cerr << "Unable to access file!\n";
return -1;
}
int N = -1, n = 0;
infile >> N;
string str;
for (; n < N && infile; ++n) {
infile >> str;
v.push_back(str);
}
if (n != N)
cerr << "ERROR, read less than " << N << " strings!!\n\n";
return 0;
}
int main() {
vector<string> v;
if(reading(v, "test.txt")) {
cerr << "Din't read file, exiting...\n";
return -1;
}
for(size_t i = 0; i < v.size(); ++i)
cout << v[i] << "\n";
return 0;
}
Output:
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
String
String2
String3
Edit:
We have to pass a pointer to what we want to modify (that is, the string*), otherwise the changes we apply won't take place. Test it yourself, pass a string* as a parameter instead of string**, modify the body of the function and she what happens.
To get the idea, imagine we want to write to the pointer, the new address, which new gave us and holds the memory requested. We do write that address inside the function, but when the function terminates, we want the changes to be persistent. See my Functions in C as an example.
Allocate an array on the heap, like this:
std::string* stringArr = new std::string[(place amout of strings here)];
and don't forget to delete it at the end of main()
delete stringArr[];
Variables / arrays on the heap are dynamic so the size doesn't have to be fixed!
std::string* → This is a pointer that points to the address of the beginning of this array in your memory. (Just to let your computer know where it is)
stringArr → the name of the array
new → allocates new memory
std::string[size] → says how much to allocate
I've seen some answers that were talking about "vectors". If you wanna use them you could have a look at this page for more info! →
Vector documentation
use a vector
#include <vector>
#include<fstream>
#include <iostream>
using namespace std;
void reading(int & count, vector<string> * strings) {
ifstream fd("text.txt");
fd >> count;
string T;
for (int i=0; i<count; i++)
{
fd >> T;
strings->push_back(T);
}
fd.close();
}
int main() {
int count=0;
vector<string> strings;
reading(count, &strings);
for (int i=0; i<count; i++)
cout << strings[i] << endl;
}

Sorting Dynamic Array With Data File

I have an assignment in which I have to read from a file called ("random.txt") output the total and copy the file into an array dynamically. Then sort the values in the file.
Up until line 20 my programs runs fine and outputs my total values as well as all the numbers in file.
Line 21 onward also runs but then it doesn't output the total I had in line 20 when I run it and it also doesn't display the values in order.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream fin;
int n=0;
double temp;
fin.open("data.txt");
fin>>temp;
while(fin)
{
n++;
fin>>temp;
cout<<temp<<endl;
}
cout<<"Total:"<<n<<endl;
fin.close(); //Program run fine up to here.
fin.open("data.txt");
double *A;
A=new double[n];
for (int i=0;i<n-1;i++)
for (int j=i;j<n;j++)
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
for (int i=0;i<n;i++)
{
while(fin)
{
n++;
fin>>A[i];
cout<<"Array:"<<A[i]<<endl;//Program runs up to here as well but
//but now doesn't print out the total I
//had in my program above and just
//prints A[i] and its not even sorted.
}
}
fin.close();
}
I know I have a lot of errors, I'm very new to c++ so I'm still trying to learn. To be quite honest I don't know what I'm doing starting from line 32. I understand that I sorted my array from 24-31, but I don't know how to read my file into my array or how to format it.
Your array load is in the wrong location. It should be before the sort, but after the allocation:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream fin("data.txt");
double temp;
size_t n = 0;
while(fin >> temp)
{
std::cout << temp << ' ';
++n;
}
std::cout << "Total: "<< n << endl;
fin.close();
if (n > 0)
{
fin.open("data.txt");
double *A = new double[n];
for (int i=0; i<n && fin >> A[i]; ++i);
fin.close();
for (int i=0;i<n-1;i++)
{
for (int j=i;j<n;j++)
{
if (A[i]>A[j])
{
int temp=A[i];
A[i]=A[j];
A[j]=temp;
}
}
}
for (int i=0; i<n; i++)
cout << "Array[" << i << "]: " << A[i] << endl;
delete [] A;
}
}
Honestly, there are much better ways to do this. Using the standard library containers, this entire menagerie is reduced to...
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
int main()
{
std::ifstream fin("data.txt");
std::vector<double> A{
std::istream_iterator<double>(fin),
std::istream_iterator<double>() };
std::sort(std::begin(A), std::end(A));
for (auto x : A)
std::cout << x << '\n';
}
You need to assign values to the elements of A before you can sort or read from A!
Your sort in lines 24-31 is misplaced. A is defined on lines 22 and 23 but never initialized. I think you meant to read it from data.txt after reopening on line 21 but you did not.

C++ Getting values from file into array

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <fstream>
using namespace std;
void make_array(ifstream& num, int (&array)[50]);
int main()
{
ifstream file; // variable controlling the file
char filename[100]; /// to handle calling the file name;
int array[50];
cout << "Please enter the name of the file you wish to process:";
cin >> filename;
cout << "\n";
file.open(filename);
if (file.fail()) {
cout << "The file failed to open.\n";
exit(1);
} else {
cout << "File Opened Successfully.\n";
}
make_array(file, array);
file.close();
return (0);
}
void make_array(ifstream& num, int (&array)[50])
{
int i = 0; // counter variable
while (!num.eof() && i < 50) {
num >> array[i];
i = i + 1;
}
for (i; i >= 0; i--) {
cout << array[i] << "\n";
}
}
I am trying to read values from a file to an array using fstream. When I try to display the contents of the array, I get 2 really big negative numbers, and then the contents of the file.
Any ideas what I did wrong?
Your use of num.get(array[i]) doesn't match any of its signatures. See get method description. What you want is this:
array[i] = num.get();
As discussed in the comments, you try to read an integer which is encoded as text. For this, you need to use operator>> (which reads any type encoded as string) instead of get (which reads a single byte):
num >> array[i];

C++ program to read a txt file and sort data

I'm a physics PhD student with some experience coding in java, but I'm trying to learn C++.
The problem I'm trying to solve is to read in data from a .txt file and then output all the numbers > 1000 in one file and all those <1000 in another.
What I need help with is writing the part of the code which actually reads in the data and saves it to an array. The data itself is only separated by a space, not all on a new line, which is confusing me a bit as I don't know how to get c++ to recognise each new word as an int. I have canabalised some code I have got from various sources online-
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
#include<cmath>
using namespace std;
int hmlines(ifstream &a) {
int i=0;
string line;
while (getline(a,line)) {
cout << line << endl;
i++;
}
return i;
}
int hmwords(ifstream &a) {
int i=0;
char c;
a >> noskipws >> c;
while ((c=a.get()) && (c!=EOF)){
if (c==' ') {
i++;
}
}
return i;
}
int main()
{
int l=0;
int w=0;
string filename;
ifstream matos;
start:
cout << "Input filename- ";
cin >> filename;
matos.open(filename.c_str());
if (matos.fail()) {
goto start;
}
matos.seekg(0, ios::beg);
w = hmwords(matos);
cout << w;
/*c = hmchars(matos);*/
int RawData[w];
int n;
// Loop through the input file
while ( !matos.eof() )
{
matos>> n;
for(int i = 0; i <= w; i++)
{
RawData[n];
cout<< RawData[n];
}
}
//2nd Copied code ends here
int On = 0;
for(int j =0; j< w; j++) {
if(RawData[j] > 1000) {
On = On +1;
}
}
int OnArray [On];
int OffArray [w-On];
for(int j =0; j< w; j++) {
if(RawData[j]> 1000) {
OnArray[j] = RawData[j];
}
else {
OffArray[j] = RawData[j];
}
}
cout << "The # of lines are :" << l
<< ". The # of words are : " << w
<< "Number of T on elements is" << On;
matos.close();
}
But if it would be easier, i'm open to starting the whole thing again, as I don't understand exactly what all the copied code is doing. So to summarise, what I need is it to-
Ask for a filepath in the console
Open the file, and store each number (separated by a space) as an element in a 1D array
I can manage the actual operations myself I think, if I could just get it to read the file the way I need.
Thanks very much
Using C++11 and the Standard Library makes your task fairly simple. This uses Standard Library containers, algorithms, and one simple lambda function.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <fstream>
#include <string>
#include <vector>
int main()
{
std::string filename;
std::cout << "Input filename- ";
std::cin >> filename;
std::ifstream infile(filename);
if (!infile)
{
std::cerr << "can't open " << filename << '\n';
return 1;
}
std::istream_iterator<int> input(infile), eof; // stream iterators
std::vector<int> onvec, offvec; // standard containers
std::partition_copy(
input, eof, // source (begin, end]
back_inserter(onvec), // first destination
back_inserter(offvec), // second destination
[](int n){ return n > 1000; } // true == dest1, false == dest2
);
// the data is now in the two containers
return 0;
}
Just switch the type of variable fed to your fistream, created from new std:ifstream("path to file") into a int and c++ will do the work for you
#include <fstream> //input/output filestream
#include <iostream>//input/output (for console)
void LoadFile(const char* file)
{
int less[100]; //stores integers less than 1000(max 100)
int more[100]; //stores integers more than 1000(max 100)
int numless = 0;//initialization not automatic in c++
int nummore = 0; //these store number of more/less numbers
std::ifstream File(file); //loads file
while(!file.eof()) //while not reached end of file
{
int number; //first we load the number
File >> number; //load the number
if( number > 1000 )
{
more[nummore] = number;
nummore++;//increase counter
}
else
{
less[numless] = number;
numless++;//increase counter
}
}
std::cout << "number of numbers less:" << numless << std::endl; //inform user about
std::cout << "number of numbers more:" << nummore << std::endl; //how much found...
}
This should give you an idea how should it look like(you shoudnt use static-sized arrays tough) If you got any probs, comment back
Also, please try to make nice readable code, and use tabs/ 4 spaces.
even though its pure C, this might give you some hints.
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#define MAX_LINE_CHARS 1024
void read_numbers_from_file(const char* file_path)
{
//holder for the characters in the line
char contents[MAX_LINE_CHARS];
int size_contents = 0;
FILE *fp = fopen(file_path, "r");
char c;
//reads the file
while(!feof(fp))
{
c = fgetc(fp);
contents[size_contents] = c;
size_contents++;
}
char *token;
token = strtok(contents, " ");
//cycles through every number
while(token != NULL)
{
int number_to_add = atoi(token);
//handle your number!
printf("%d \n", number_to_add);
token = strtok(NULL, " ");
}
fclose(fp);
}
int main()
{
read_numbers_from_file("path_to_file");
return 0;
}
reads a file with numbers separated by white space and prints them.
Hope it helps.
Cheers