Codeblocks why is my code unable to open my .csv file - file

This is part of my code, of course I have #include fstream>, and to basically run you throught what the code should do at this point is open a file I have name "flights.csv" and in a function called readFlights count how many flights are in the file and then return the size, but when ran it returns a size of 0 when there are 5 in the file, and gives me my error file open message.
int main()
{
ifstream in("flights.csv");
if(!in.is_open()) cout << "ERROR: File open" << endl;
Flights flightsList[100];
const int SIZE = readFlights(in, flightsList);
cout << "Size: " << SIZE <<endl;
here is the function for counting the size and putting it into an array.
int readFlights(ifstream& in, Flights flightsList[100]){
//Reads the file flights.csv and returns a size used for array.
string pdStore, dmStore;
int size= 0;
while(in.good()){
getline(in, flightsList[size].fromCity,',');
getline(in, flightsList[size].toCity,',');
getline(in, pdStore,',');
flightsList[size].priceDollars = stoi(pdStore);
getline(in, dmStore,'\n');
flightsList[size].distanceMiles = stoi(dmStore);
size++;
}
return size;
}
I thought it was interesting but I don't know if this is necessary but inside code blocks the .csv part of the file in ifstream in("flights.csv"); was underlined with the red jagged lines.

I found the answer, I had no clue I had to include the file into the project folder itself...

Related

Utilizing the <filesystem> library; visualStudios

I'll cut the the short of it. I'm attempting to understand the filesystem library but there's very little information I've been able to find. I managed to get it to compile and understand the filesystem::path type variable really well but don't seem to understand how to get filesystem::directory_iterator to work properly. I'm not sure if I'm using it for a purpose it wasn't design for. So here is what I'm attempting to do:
I wanted to create a program that opens every text file within a specified folder. For this I need to obtain the folder name and path but I want the program to be able to obtain this information on itself and dynamically so if I add or remove textFiles it'll have the logic to function.
I'm able to create a directory_iterator variable that it manages to hold the first file with me just giving it the directory like this:
const char address[]{ "C:\\Users\\c-jr8\\ProgramBranch\\PersonalPlatform\\log extruder\\logs" };
fs::directory_iterator myIterator(address);
When testing the code in the folder I have four textFiles called "attempt 1" to "attempt 4". When reading the information on:
https://learn.microsoft.com/en-us/cpp/standard-library/directory-iterator-class?view=vs-2019#op_star
It mentions two functions to move the path object within the iterator to the next file. The first is increment(), which is the intendent method for iterating through the files, and operation++().
Now increment() hasn't been able to work for me cause it takes in a erro_code type variable and I haven't been able to find much information about how to implement this with the filesystem_errorcode variable or however it's meant to be used. The operation++() works beautifully and provides me with the path to every file but I was having issues with managing the code to detect when the operate++() functions leads to no other files. Once it iterates through every file it sorts of crashes when it keeps moving to the next. Here's that piece of code:
string tempString;
for (int i = 0; i < 5; i++) { //Here the limiting is 5 so it'll iterate onces more than the numbers of files unpurpose to see how it responses.
tempString = myIterator.operator*().path().generic_string();
ifstream tempFile(tempString);
if (!tempFile.is_open()) {
cout << "Looking at file: " << i + 1 << "; failed to open." << endl << endl;
cin.get();
return 0;
}
{
//do things with file...
}
tempFile.close();
myIterator.operator++();
}
What I want if to find a way to stop the for loop once it the iterator goes off the final file.
whichever information about how the filesystem library works it would be very much appreciated.
std::directory_iterator is a classic iterator that allows for iterating over ranges, and those are usually designated by a pair of iterators, one indicating the beginning of a sequence and another representing the past-the-end iterator.
Some iterator types, like those providing access to streams, don't have an actual end location in memory. A similar situation applies to a directory iterator. In such a case, the idiomatic approach is to use a default-constructed iterator object that will serve as an end indicator.
Having said that, you could rewrite your loop to:
for (fs::directory_iterator myIterator(address), end{}; myIterator != end; ++myIterator) {
Alternatively, you can utilize a range-based for loop:
for (auto& p : fs::directory_iterator(address)) {
tempString = p.path().generic_string();
// ...
Also, note that iterators' interface is supposed to look/behave like a pointer, hence it uses operator overloading to allow for concise syntax. So instead of:
myIterator.operator++();
you should be using:
++myIterator;
Similarly, instead of:
myIterator.operator*().path().generic_string();
juse use:
(*myIterator).path().generic_string();
or:
myIterator->path().generic_string();
You should compare myIterator with a default constructed directory_iterator to check if the last file has been processed. You can also use a much simpler form to access the operators (shown in the code below):
string tempString;
// loop until myIterator == fs::directory_iterator{}
for(size_t i = 1; myIterator != fs::directory_iterator{}; ++i) {
// access path() through the iterators operator->
tempString = myIterator->path().generic_string();
ifstream tempFile(tempString);
if(!tempFile.is_open()) {
cout << "Looking at file: " << i << "; failed to open." << endl << endl;
cin.get();
return 0;
}
{
std::cout << tempString << " opened\n";
}
// tempFile.close(); // closes automatically when it goes out of scope
// simpler form to use myIterator.operator++():
++myIterator;
}
An even simpler approach would be to use a range-based for-loop:
for(const fs::directory_entry& dirent : fs::directory_iterator(address)) {
const fs::path& path = dirent.path();
ifstream tempFile(path);
if(!tempFile) {
cout << "Looking at file: " << path << "; failed to open.\n\n";
cin.get();
return 0;
}
std::cout << path << " opened\n";
}

How to read a single line of txt file word by word [C++]

I need to read a single line of a given file word by word.
The file is a register of exam grades by different students. In particular, for any student there is a first
line formatted as follows:
-name- -surname-
Then, there is a second line reporting the grades of every exam using the following format:
-grade 1- -grade 2- -grade 3- [...] -grade n-
I created a class Student and want to put the grades in an array of int.
I know how to read the file word by word, but I have no idea how to stop once the grades from a student are over (since I don't know how may grades any given student has beforehand).
I thought to write a while repetition statement, but I have no idea what the condition could be.
Is there a way to read a line word by word and then stop reading once the line is over?
This is what I managed to write until now:
cout << "Inserisci il nome del file da analizzare: " << endl;
cin >> _filename;
fstream myfile;
myfile.open(_filename);
if (myfile.is_open())
{
myfile >> _name >> _surname >> ; //reading name and surname
}
Read a line of text using std::getline.
Read each token from the line by using a std::istringstream.
std::string line;
if ( ! std::getline(myfile, line) )
{
// Problem reading the line.
// Deal with error.
}
else
{
// Read line successfully.
std::istringstream str(line);
std::string token;
while ( str >> token )
{
// Use token.
}
}

How to call on a renamed file in another function? (Visual C++)

So, I'm trying to create a text file that can be written to and used to seed a random number generator, but I need to be able to write to and call on the file in all of my functions. The file has to be named with the user's first and last name so I found some code that would create a text file and rename it, I'm just having trouble calling the file in my other functions. I included the beginning part of one of my other functions after the code for the text file creation. I'm going to need to send a time stamp to the file and use that time to seed my RNG.
int user_file_name()
{
string tstamp = get_timestamp();
//Creating input/output file using user's name
ofstream user_file;
string filename;
cout << "What is your first and last name?\n" << endl;
getline(cin, filename);
filename += ".txt";
cout << "Thank you, " << filename << "." << endl << endl;
user_file.open(filename.c_str());
user_file << tstamp;
user_file.close();
return 0;
}
int addition()
{
char DIFFICULTY;
difficulty_menu();
cin >> DIFFICULTY;
get_timestamp();
string tstamp = get_timestamp();
Why not just have user_file_name return the string filename instead of just an int? You can then store that filename somewhere so that other areas of your program can access it.

Simple search program using arrays help me

When the user types in a word the program is searching for a match in an array, if there is a match the program prints out the string from the array.The code below does just that. My goal is to make it so when a word matches with a a word in the array the program should print an info not only the word. I thought I can fill the array with functions, but its not working. Is it even possible ?
I am using league of legend hero names because they are a lot and I know them and it doesent take me a lot of time to think of names that way :D
The idea is if the user types in voly, the program finds voly in the array and prints out(for example) his starting life, armor, mr and so on.
I tryed a lot of thing with functions but I cant make it work.
#include <iostream>
#include <string>
using namespace std;
string voly(string holder,string heroName);
int main(){
const int numH = 10;
string holder;
string heroName;
string heroList[numH] = {"voly", "teemo", "vladimir", "morgana", "jax", "ekko", "anivia", "nunu", "ashe", "tresh" };
cout << "Enter hero name.\n" << endl;
cin >> heroName;
for (int i = 0; i < numH; i++){
holder = heroList[i];
if (heroName == holder){
cout << holder << endl;
}
}
system("PAUSE");
return 0;
}
string voly(string holder, string heroName) {
cout << "Voly is the best" << endl;
}
Try to learn about structs. You can utilize them to encapsulate all hero information in a hero struct, as follows. This serves as kind of a prototype for each hero:
struct hero {
string name;
int hp;
int mana;
float mreg;
...
void printMe() { cout << 'hp: ' << hp << endl << 'mana: ' << mana << endl << ...; }
}
Using the printMe() function of that specific hero object, you can print its values.
Then, for each hero, create a struct object and add them to the array.
hero* pointer = new hero[numH];
pointer[0] = new hero {
name: "voly",
hp: 150
};
pointer[1] = new hero {
...
};
(Try considering some import function via a .CSV file or so.)
By using your for loop, compare the name:
for (int i = 0; i < numH; i++){
if (heroName == pointer[i].name){
pointer[i]->printMe();
}
}
Try using Google to find tutorials on that. Unfortunately, I'm not quite sure about the syntax in C++, maybe someone can help me out.
Good Luck!

Searching a particular string in a large file

I am making program in C which can search for a specific string in a large .txt file and count it and then print it out. But it seems that something have go wrong, cause the output of my program is different from that of the two text editor. According to the text editor, there are totally 3000 words,in this case I search for the word "make", in that .txt file. But the output of my program is just 2970.
I cannot find out the problem of my program. So I am curios about how could a text editor search for a specific string so accurately? How do people implement that? Can any people show me some code in C?
To make things clear: that is a large .txt file, 20M or so, containing lots of characters. So I think it's not so good to read it into memory all at once. I have implement my program by splitting my program in to pieces and then scan all of those for parsing. However, it fail some way.
Maybe I should put the code here. Wait a minute please.
The code is kinda long, 70 lines or so. I have put it on my github, if you have any interest, please help. https://github.com/walkerlala/searchText
note that the only related file is wordCount.c and testfile.txt which goes like:
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
char arr[51];
int flag=0;
int flag2=0;
int flag3=0;
int flag4=0;
int pieceCount(FILE*);
int main()
{
//the file in which I want to search the word is testfile.txt
//I have formatted the file so that it contain no newlins any more
FILE* fs=fopen("testfile.txt","r");
int n=pieceCount(fs);
printf("%d\n",n);
rewind(fs); //refresh the file...
static bool endOfPiece1=false,endOfPiece2=false,endOfPiece3=false;
bool begOfPiece1,begOfPiece2,begOfPiece3;
for(int start=0;start<n;++start){
fgets(arr,sizeof(arr),fs);
for(int i=0;i<=46;++i){
if((arr[i]=='M'||arr[i]=='m')&&(arr[i+1]=='A'||arr[i+1]=='a')&&(arr[i+2]=='K'||arr[i+2]=='k')&&(arr[i+3]=='E'||arr[i+3]=='e')){
flag+=1;
//continue;
}
}
//check the border
begOfPiece1=((arr[1]=='e'||arr[1]=='E'));
if(begOfPiece1==true&&endOfPiece1==true)
flag2+=1;
endOfPiece1=((arr[47]=='m'||arr[47]=='M')&&(arr[48]=='a'||arr[48]=='A')&&(arr[49]=='k'||arr[49]=='K'));
begOfPiece2=((arr[1]=='k'||arr[1]=='K')&&(arr[2]=='e'||arr[2]=='E'));
if(begOfPiece2==true&&endOfPiece2==true)
flag3+=1;
endOfPiece2=((arr[48]=='m'||arr[48]=='M')&&(arr[49]=='a'||arr[49]=='A'));
begOfPiece3=((arr[1]=='a'||arr[1]=='A')&&(arr[2]=='k'||arr[2]=='K')&&(arr[3]=='e'||arr[3]=='E'));
if(begOfPiece3==true&&endOfPiece3==true)
flag4+=1;
endOfPiece3=(arr[49]=='m'||arr[49]=='M');
}
printf("%d\n%d\n%d\n%d\n",flag,flag2,flag3,flag4);
getchar();
return 0;
}
//the function counts how many pieces have I split the file into
int pieceCount(FILE* file){
static int count=0;
char arr2[51]={'\0'};
while(fgets(arr2,sizeof(arr),file)){
count+=1;
continue;
}
return count;
}
You can do this quite simply just by having a rolling buffer. You don't need to break the file into sections.
#include <stdio.h>
#include <string.h>
int main(void) {
char buff [4]; // word buffer
int count = 0; // occurrences
FILE* fs=fopen("test.txt","r"); // open the file
if (fs != NULL) { // if the file opened
if (4 == fread(buff, 1, 4, fs)) { // fill the buffer
do { // if it worked
if (strnicmp(buff, "make", 4) == 0) // check for target word
count++; // tally
memmove(buff, buff+1, 3); // shift the buffer down
} while (1 == fread(buff+3, 1, 1, fs)); // fill the last position
} // end of file
fclose(fs); // close the file
}
printf("%d\n", count); // report the result
return 0;
}
For simplicity I stopped short of making the search word "softer" and allocating the correct buffer and various sizes, since that wasn't in the question. And I have to leave something for OP to do.

Resources