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.
Related
I have to create program that takes text from file line-by-line, sorts it in lexicographic order and then if any word occured in previous line replace it with "-".
So far I've got sorting figured out, but I feel like I've hit a wall with replacing words that occured before.
My code so far looks like this:
#include <iostream>
#include <list>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string.h>
using namespace std;
int main()
{
const string A = "abcdefghijklmnopqrstuwvxyz " ;
list<string> lista;
string line;
ifstream myfile("./file.txt");
while(!myfile.eof())
{
getline(myfile, line);
lista.push_back(line);
}
vector<string> l;
lista.sort();
copy(begin(lista), end(lista), back_inserter(l));
for(unsigned int i=0; i<l.size(); i++) // check if sorted properly
cout << l[i] << endl;
for(unsigned int i=0; i<l.size()-1; i++)
{
unsigned int end=0;
unsigned int j=1;
while(l[i][end]==l[j][end])
{
end++;
j++;
}
l[i].erase(0, end);
l[i].insert(0, "- ");
}
for(unsigned int i=0; i<l.size(); i++)
cout << l[i] << endl;
return 0;
}
As you can see, I attempted doing this replacement thing, but to no success.
Any help would be greatly appreciated!
Making a program that reads integers from a file and creates an array, I have that part completed however I am trying to figure out how to change the SIZE value depending on how many ints are in the file. This file has 15 integers but another file may have more and this array will not take in all the ints.
using namespace std;
const int SIZE = 15;
int intArray[SIZE];
void readData(istream& inFile) {
for (int i = 0; i < SIZE; i++){
inFile >> intArray[i];
cout << intArray[i] << " ";
}
}
int main() {
ifstream inFile;
string inFileName = "intValues.txt";
inFile.open(inFileName.c_str());
int value, count = 0;
while(inFile >> value){
count += 1;
}
cout << count;
readData(inFile);
return 0;
}
As you can see I have a while loop counting the number of ints in the file however when I assign that to the size value I was running into many different issues.
A fixed-sized array simply cannot be resized, period. If you need an array whose size can change at runtime, use std::vector instead.
More importantly, you are reading through the entire file just to count the number of integers, and then you are trying to read the values from where the previous loop left off. You are not seeking the ifstream back to the beginning of the file so you can re-read what you have already read.
Try something more like this instead:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
int value, count = 0;
while (inFile >> value){
++count;
}
cout << count;
std::vector<int> intArray;
intArray.reserve(count);
inFile.seekg(0);
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
return 0;
}
Alternatively, don't even bother counting the integers, just let the std::vector grow as needed, eg:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int main() {
string inFileName = "intValues.txt";
ifstream inFile(inFileName.c_str());
vector<int> intArray;
int value;
while (inFile >> value){
intArray.push_back(value);
cout << value << " ";
}
// use intArray as needed...
// you an get the count from intArray.size()
return 0;
}
Our professor wants us to fix the code which counts the amount of values in a data.txt file and computes their average. Here is the code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int main(int argc, char *argv[])
{
string s;
ifstream f;
int nItems;
double * data;
double sum=0;
vector < double > data2;
double item;
cout <<"File name: ";
cin >> s;
f.open (s.c_str() );
while (! f.eof() )
{
f >> item;
data2.push_back(item);
}
for (int i =0; i < nItems; i++)
{
sum += data[i];
}
cout << "The average is " << sum/nItems <<".\n";
cout << "Press the enter key to continue ...";
cin.get();
return EXIT_SUCCESS;
}
His instructions were:
Modify code worked on today so that the average of data in vector < double > data is computed properly. Right now the code just gives you a value which isn't the average.
I tried changing the nItems variable into 12 and that seemed to work, but the goal of the code is to determine nItems and use that to find the average, which I can't seem to figure out.
You use data for which you haven't allocated any memory when you summarise That causes undefined behaviour. You've stored your values in data2. Remove variables you don't need. Also, using namespace std is considered bad practice.
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <numeric> // std::accumulate
int main(int, char**) {
std::string filename;
std::cout << "File name: ";
std::cin >> filename;
std::ifstream f(filename); // no need for .c_str()
std::vector<double> data;
double item;
// instead of checking for eof, check if extraction succeeds:
while(f >> item) {
data.push_back(item);
}
// a standard way to sum all entries in a container:
double sum = std::accumulate(data.begin(), data.end(), 0.);
std::cout << "The sum is " << sum << "\n";
// use the containers size() function. it returns the number of items:
std::cout << "The average is " << (sum / data.size()) << "\n";
}
Hey looks like you weren't reading the numbers in from the txt file.
Here I look through the input file once just to count how many numbers there are
so I can make the array.
Then I look through it again to fill the array.
#include <cstdlib>
#include <iostream>
#include <fstream>
// f here stands for find, fstream gives you files
using namespace std;
int main(int argc, char *argv[]) {
string s;
ifstream f;
// input file stream
int nItems;
double * data;
double sum=0;
cout << "File name: ";
cin >> s;
f.open (s.c_str() );
// s.c_str will return a char array equivalent of the string s
nItems=0;
int input =0;
while (f >> input) {//first loop reading through file to count number of items
nItems++;
}
f.close();
data = new double[nItems]; //Make the array
f.open (s.c_str() );//open file for second read
int i=0;
while (f >> input) {//Second loop through file fills array
data[i] = input;
i++;
}
f.close();
for (int i = 0; i < nItems; i++) {
sum += data[i];
}
cout << "The average is " << sum / nItems << ".\n";
cout << endl;
system("pause");
return 0;
}
Whenever I try to see the contents inside the vector I get "segmentation fault" any idea why that is? Do I not read in the values properly?
#include <iostream>
#include <cstdlib> // atoi function
#include <vector>
#include <fstream>
using namespace std;
vector<int> list ; // global vector
int main (int args , char * argv[])
{
ifstream in(argv[1]);
//ofstream out(argv[2]);
int listSize = atoi (argv[2]);
cout << listSize << endl;
int i = 0;
cout << argv[1] << endl;
in.open(argv[1]);
while (i < listSize)
{
in >> list[i];
cout << "test2" << endl;
i++;
}
in.close();
for( int k=0; k <listSize; k++){
cout<< list[k] << endl;
}
return 0;
}
the text file contains these numbers:
5 6 7 11 12 13
A vector doesn't automatically come with slots. You have to either reserve slots or use push_backto append items to the vector:
//...
int value;
in >> value;
list.push_back(value);
Read what's in the file using getline. See sample code below:
ifstream InFile(argv[1], ios::in); /*Open file from arg[1]*/
std::string LineContent;
getline(InFile, LineContent); /*Save line per line */
With your line saved in a string, you can now transfer the data from that string to the vector, see:
vector<int> list;
list.push_back(atoi(LineContent.c_str()));
Now, you can print out what's in the file:
for (int i = 0; i < list.size(); i++)
cout << list[i] << endl;
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();
}