I want to "quick sort" the array that I have read from a .txt file; but the code is generating an error. It says "Expected primary expression before "input" ".
Any help is appreciated. This is the code. Thank you.
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
void quickSort(int tabele[], int majtas, int djathtas){
if(majtas<djathtas){
int vendPivot = ndarja(tabele, majtas, djathtas);
/* rendit sipas rradhes elementet para dhe pas vendPivot */
quickSort(tabele, majtas,vendPivot-1);
quickSort(tabele,vendPivot+1, djathtas);
}
}
vector<int> lexoTabele(){
vector<int> data;
ifstream inFile;
inFile.open("detyraekursit.txt");
if (!inFile.is_open()) {
cout << "Unable to open file";
exit(1); // terminate with error
}
int x;
cout<<"Vektori INPUT para renditjes ";
while (inFile >> x) {
data.push_back(x);
}
inFile.close();
return data;
}
int main() {
vector<int> input = lexoTabele();
int x,y;
for(int i = 0;i < input.size();i++) {
cout<< i << ", " << input[i];
}
quickSort(vector<int>input,x,y);
return 0;
}
Related
So, the binary file literally stores just one struct array
#include <string>
#include <fstream>
using namespace std;
struct Card{
char symbol;
int color;
int id;
};
int main(){
int numcards = 12;
Card *cardArray[numcards];
ifstream arch;
arch.open("casoPruebaParte1.dat", ios::binary);
if(!arch.is_open()){
cout<<"Error al abrir el archivo\n";
exit(1);
}
numcards = 12;
arch.read((char*)&cardArray, numcards*sizeof(Card));
for(int i=0; i<numcards; i++ ){
cout << cardArray[i]->id << endl;
}
arch.close();
return 0;
}
the error is: segmentation fault (core dumped) and debugging shows this:
error in line 30 ( cout << cardArray[i]->id << endl;)
I am trying to write a code which lists all words used in a text file without repeating. I succeeded to list all the words but I always get repeating ,the if statement line 17 always gives the value of 0.I have no idea why , the words are listed properly in the vector. Any suggestion ?
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class reading {
public:
string word;
vector<string> words;
};
int checkifexist(string word) {
reading readingobject;
bool exist = false;
for (int i = 0; i < readingobject.words.size(); i++) {
if (word == readingobject.words[i]) {
exist = true;
break;
}
}
return exist;
}
int main() {
reading readingobject;
ifstream inFile;
inFile.open("Book.txt");
if (inFile.fail()) {
cout << "file didn't open" << endl;
exit(1);
}
readingobject.word.resize(1);
while (!inFile.eof()) {
inFile >> readingobject.word;
if (checkifexist(readingobject.word) == 1)
continue;
cout << readingobject.word << endl;
readingobject.words.push_back(readingobject.word);
}
return 0;
}
Inside of checkifexist(), you are creating a new reading object, whose words vector is empty, so there is nothing for the loop to do, and the function returns 0.
You need to instead pass in the reading object from main() as an input parameter, eg:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
class reading {
public:
vector<string> words;
};
bool checkifexist(const reading &readingobject, const string &word)
{
for (size_t i = 0; i < readingobject.words.size(); ++i) {
if (word == readingobject.words[i]) {
return true;
}
}
return false;
/* alternatively:
return (std::find(readingobject.words.begin(), readingobject.words.end(), word) != readingobject.words.end());
*/
}
int main()
{
reading readingobject;
string word;
ifstream inFile;
inFile.open("Book.txt");
if (!inFile) {
cout << "file didn't open" << endl;
return 1;
}
while (inFile >> word) {
if (checkifexist(readingobject, word))
continue;
cout << word << endl;
readingobject.words.push_back(word);
}
return 0;
}
Alternatively, when it comes to tracking unique elements, you can use a std::set instead of a std::vector, eg:
#include <iostream>
#include <fstream>
#include <set>
using namespace std;
class reading {
public:
set<string> words;
};
int main()
{
reading readingobject;
string word;
ifstream inFile;
inFile.open("Book.txt");
if (!inFile) {
cout << "file didn't open" << endl;
return 1;
}
while (inFile >> word) {
if (readingobject.words.insert(word).second)
cout << word << endl;
}
return 0;
}
The file does open and I get the message "File opened successfully". However I can't input data from the array in file "random.csv" into my inputFile object.
The data in random.csv is:
Boston,94,-15,65
Chicago,92,-21,72
Atlanta,101,10,80
Austin,107,19,81
Phoenix,112,23,88
Washington,88,-10,68
Here is my code:
#include "main.h"
int main() {
string item; //To hold file input
int i = 0;
char array[6];
ifstream inputFile;
inputFile.open ("random.csv",ios::in);
//Check for error
if (inputFile.fail()) {
cout << "There was an error opening your file" << endl;
exit(1);
} else {
cout << "File opened successfully!" << endl;
}
while (i < 6) {
inputFile >> array[i];
i++;
}
for (int y = 0; y < 6; y++) {
cout << array[y] << endl;
}
inputFile.close();
return 0;
}
Hello and welcome to Stack Overflow (SO). You can use std::getline() to read each line from the file, and then use boost::split() to split each line into words. Once you have an array of strings for each line, you can use a container of your liking to store the data.
In the example below I've used an std::map that stores strings and a vector of ints. Using a map will also sort the entrances using the key values, which means that the final container would be in alphabetical order. The implementation is very basic.
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/split.hpp>
#include <ctype.h>
typedef std::map<std::string,std::vector<int>> ContainerType;
void extract(ContainerType &map_, const std::string &line_)
{
std::vector<std::string> data;
boost::split(data, line_, boost::is_any_of(","));
// This is not the best way - but it works for this demo.
map_[data[0]] = {std::stoi(data[1]),std::stoi(data[2]),std::stoi(data[3])};
}
int main()
{
ContainerType map;
std::ifstream inputFile;
inputFile.open("random.csv");
if(inputFile.is_open())
{
std::string line;
while( std::getline(inputFile,line))
{
if (line.empty())
continue;
else
extract(map,line);
}
inputFile.close();
}
for (auto &&i : map)
{
std::cout<< i.first << " : ";
for (auto &&j : i.second)
std::cout<< j << " ";
std::cout<<std::endl;
}
}
Hope this helps.
I'd like to know how to read a file using streams but also using them inside a function.
So far my code is;:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;
void burbuja(int[]);
void imprimeArreglo (int[],int);
void leeArchivo(string&);
int arreglo[10];
int i;
void burbuja (int a[])
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(a[i]>a[j])
{
int temp=a[i]; //swap
a[i]=a[j];
a[j]=temp;
}
}
}
}
void imprimeArreglo(int a[],int tam)
{
for(int i=0;i<tam;i++)
cout << a[i] << " ";
}
void leeArchivo(string& nombre)
{
string filename = nombre;
ifstream myfile(filename);
string line;
if (myfile.is_open()) {
while ( getline (myfile,line) )
{
cout << line << '\n';
}
myfile.close();
}
else cout << "Unable to open file";
}
int main()
{
string nombre = "arr.txt";
leeArchivo(nombre);
cin >> i ;
return 0;
}
I'd like to be able to call leeArchivo("arr.txt") from the main method.
With this I get the errors:
Error: bubble.cpp(37,14):'ifstream' is not a member of 'std'
Error: bubble.cpp(37,19):Statement missing ;
Error: bubble.cpp(39,20):Undefined symbol 'file'
Error: bubble.cpp(39,25):Could not find a match for 'std::getline(undefined,std::basic_string<char,std::string_char_traits<char>,std::allocator<char>>)'
What am I missing here? (I'm new to C++)
The file I'm trying to read has the following structure:
<number>
<number> <number> <number> ...
E.G.:
5
19 28 33 0 1
=========================================
EDIT:
I'm using Borland C++ 5.02
EDIT 2:
Updated code, using Geany Now error is: BUBBLE.cpp:38:25: error: no matching function for call to 'std::basic_ifstream<char>::basic_ifstream(std::string&)'
That's particularly odd behavior with ifstream. Try this edit:
void leeArchivo(const string&);
void leeArchivo(const string& nombre)
{
ifstream file(nombre.c_str());
string line;
while(getline(file,line)) {
cout << line << endl;
}
}
int main()
{
leeArchivo("arr.txt");
return 0;
}
Also, use:
#include <cstdlib>
Instead of:
#include <stdlib.h>
I tried to create a program that uses an input file 'cardList.txt' that contains:
Schmidt, Helga
Alvarez, Ruben
Zowkowski, Aaron
Huang, Sun Lee
Einstein, Beverly
and I wanted to sort this alphabetically by last name.
main:
#include <iostream>
#include <fstream>
#include <string>
#include "insertsortFunct.h"
using namespace std;
int main(void){
ifstream inData;
ofstream outData;
const int listSize = 5;
char cardList[listSize][25];
instruct();
openFile(inData, outData);
buildList(cardList, inData);
inData.close();
sortList(cardList, listSize);
cout << endl << "Your list is sorted" << endl;
writeFile(cardList, outData);
outData.close();
return 0;
}
I defined these functions in a separate file:
#include "insertsortFunct.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
void instruct(void){
cout << "The program insertSort.cpp reads the file, cardList.txt " <<
"into an array and" << endl;
cout << "sorts the array using the selection sort algorithm." << endl;
cout << "The sorted array is written to a file named cardList.srt." <<
endl;
}
void openFile(ifstream& inputFile, ofstream& outputFile){
inputFile.open("cardsList.txt");
if(!inputFile.is_open())
exit(1);
outputFile.open("cardsList.srt");
if(!outputFile.is_open())
exit(1);
}
void buildList(char (*array)[25], ifstream& inputFile){
for (int i = 0; i < 5; i++)
inputFile >> array[i];
}
void sortList(char (*list)[25], int length){
int firstOutOfOrder, location;
char temp[25];
for (firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++){
location = firstOutOfOrder;
while ( location > 0 && list[location - 1] > list[location]){
temp[25] = list[location][25];
list[location][25] = list[location - 1][25];
list[location - 1][25] = temp[25];
location--;
}
}
}
void writeFile(char (*array)[25], ofstream& outputFile){
for (int i = 0; i < 5; i++)
outputFile << array[i];
}
However my program only prints the instruct(); statements and nothing else appears to happen. This program is supposed to a create a file cardList.srt with the sorted list and that does not appear in my directory after compiling.
Either inputFile.is_open() or outputFile.is_open() return false and hence exit() is called.