Reading arrays from file c++ - c++

I'm trying to make a program that so far only needs to read a file and saves its content in an array. the cout was a test to see if the words would be saved to the array but it didn't work. When executed all it does is print to screen empty spaces and finally the name of the file.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <ctime>
#include <time.h>
#define MAX 10000
void readFile(fstream& wordFile, string words[], int &wordarrayLength)
{
string word;
int i=0;
while(i < MAX)
{
getline(wordFile,word);
words[i] = word;
i++;
cout << words[i] << endl;
}
wordarrayLength = i;
wordFile.close();
}
int main()
{
string words[MAX];
int arraylength;
fstream file ("words.txt", ios::in);
readFile(file,words,arraylength);
}

I was missing the file the compiler was looking for. This code works fine.

Try something like this:
//since you are updating the array pass it in by reference as well.
void readFile(fstream& wordFile, string &words[], int &wordarrayLength)
{
int i=0;
while(i < MAX)
{
//each item in the array has to be it's own string
//the previous code simply reused the same string each time
string word;
getline(wordFile, word);
words[i] = word;
cout << words[i] << endl;
i++;
}
wordarrayLength = i;
wordFile.close();
}
Unfortunately I don't have your file or compiler so I can't debug it.

Related

Lexicographical sort

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!

Changing size value for an array c++

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;
}

Writing a C++ program to print the letters of a string in a chaotic order

What I'm trying to do is this:
User enters a string (For example: "Hello")
The program returns the same string, but in a random order(It can be "elHlo" or any other order possible)
So far I've written this code, but the problem is that sometimes the randomly generated numbers are the same, so it might print the same indexes(letters) twice or more times:
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
for(unsigned int j=0; j<text.length(); j++){
int randomLetter = rand()%text.length();
cout << text.at(randomLetter);
}
return 0;
}
Can anyone help me fix it?
You can use std::shuffle (since C++11):
#include <iostream>
#include <string>
#include <random>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
std::mt19937 g(time(0));
std::shuffle(text.begin(), text.end(), g);
cout << text;
return 0;
}
Or std::random_shuffle (if you are using old specification):
#include <iostream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main(){
cout << "Say something: ";
string text;
getline(cin, text);
cout << "\nChaotic text: ";
srand(time(0));
std::random_shuffle(text.begin(), text.end());
cout << text;
return 0;
}
Instead of calling rand() one time, which can generate an index you have called before, you can keep generating a new index while keeping tracking of all generated indices in a hashtable.
std::unordered_map<int, bool> done;
for (unsigned int j = 0; j < text.length(); j++) {
int randomLetter = rand() % text.length();
while (done[randomLetter] == true) // while it's been marked as finished, generate a new index.
randomLetter = rand() % text.length();
cout << text.at(randomLetter);
done[randomLetter] = true; // mark it as finished.
}
Alternatively, you can use std::random_shuffle instead, which should save you the hassle.
std::random_shuffle (text.begin(), text.end());
std::cout << text << '\n';

Populating an array from a txt file in C++

I am having difficulty populating an array from a .txt file. I can do it without the while loop if I already know the size of the file. However, once I incorporate a while loop to extract the file size the input odes not configure correctly. Pleas take a look over my code an let me know if you see where I am going wrong.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
int main()
{
using namespace std;
const char *inName_1 = "Instance_1.txt";
const char *inName_2 = "Instance_2.txt";
int arraySize_1 = 0, arraySize_2 = 0;
int array_1[20];
int array_2[20];
int number;
ifstream A2_file_1(inName_1);
if (A2_file_1.fail())
{
cout << "File 1 not open!" << '\n';
}
while (!A2_file_1.eof())
{
arraySize_1++;
A2_file_1 >> number;
}
if (A2_file_1.is_open())
{
for (int i = 0; i < arraySize_1; i++)
{
A2_file_1 >> array_1[i];
}
A2_file_1.close();
}
cout << "The size of the array 1 is: " << arraySize_1 << endl;
for (int i = 0; i < arraySize_1; i++)
{
cout << array_1[i] << endl;
}
return 0;
}
To read an arbitrary amount of numeric values from a text-file, all you need is an std::vector and a couple of std::istreambuf_iterator objects.
Then is as simple as
std::ifstream input("Instance_1.txt");
std::vector<int> values(std::istreambuf_iterator<int>(input),
std::istreambuf_iterator<int>());
That's it. Those four lines of code (counting the empty line) will read all int values from the text file Instance_1.txt and place them into the vector values.

Using the getword function c++

Am I using the getword function wrong here? The compiler keeps telling me that there is no member function.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
using namespace std;
int OccuranceOfString(ofstream & Out)
{
string Occur;
string Temp;
int OccurLength;
int count;
cout << "please enter to string to search for";
cout << endl;
cin >> Occur;
OccurLength = Occur.length();
while(Out.getword(Temp))
{
if (Temp == Occur)
{
count ++;
}
}
return count;
}
Whats wrong with my code? I'm trying to find all occurances of a string with this function
std::ofstream has no getword function: see here.
Perhaps you're thinking of std::getline.
There is no function getword in the header files listed. You simply must construct a function that will extract words from a line. capture a line by
getline(out,line);
line will have your line of string and use line[index] to get continuous characters to be equal to a word.
You can use this
std::string::find
do something like this..
int pos = 0;
int occurrences = 0
string input = "YAaaaAH";
string find = "a";
while(pos != -1){
pos = input.find(find,pos);
occurrences++;
}
text file :
code :
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
ifstream file("DB_name_age.txt");
int index;
string name;
int age;
if(file.is_open())
{
while(file >>index >> name >>age)
{
cout << index <<" "<<name <<" "<<age << endl;
}
}else{
cout<< "file open fail" <<endl;
}
return 0;
}
visual explanation: