C++ Simple Multicolumn File Read - c++

I am trying to read a file with multiple columns to output all results with an income of over $100,000 and a GPA of less than or equal to 2.3. I'm not able to figure out which approach is correct. The file output does not even appear on the terminal. Please let me know if more specifics are needed. Here is the FILE.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inputFile;
char *student = new char[];
int salary=100000,
grades=2.3;
inputFile.open("Students.txt");
if(inputFile.fail()==1)
{
cout<<"File opening failed";
}
else
{
while(!inputFile.eof())
{
inputFile>>student;
}
inputFile.close();
}
int income=student[0];
int gpa=student[0];
for(int i=0;i!=inputFile.eof();i++)
{
income=student[i];
gpa=student[i];
if(income>=salary && gpa<=grades)
{
cout<<" "<<income<<" "<<gpa<<endl;
}
}
cin.get();
cin.get();
return 0;
}

#include <fstream>
#include <iostream>
const int MAX_STUDENTS = 100;
int main()
{
int numberOfStudents = 0;
//Instantiate read file object
std::ifstream inputFile("Student.txt");
//Instantiate an array of income
int income[MAX_STUDENTS];
float gpa[MAX_STUDENTS];
//Check if the file is open
if(inputFile.fail() == 1)
std::cout << "\nFile opening failed!\n";
else
{
while(!inputFile.eof())
{
//Read file into class
inputFile >> income[numberOfStudents];
inputFile >> gpa[numberOfStudents];
//^^**In whatever order your data members are in**
//Check if gpa and income meet requirements
if(income[numberOfStudents] > 100000 && gpa[numberOfStudents] <= 2.3)
{
/*Output student if gpa is less than or equal to 2.3 AND
greater than 100000*/
std::cout << "\nStudent #: " << numberOfStudents + 1 << ' ' << std::endl;
std::cout << income[numberOfStudents] << ' ';
std::cout << gpa[numberOfStudents] << ' ';
std::cout << ' ' << std::endl;
}
//Increase number of students
numberOfStudents++;
}
//Close file
inputFile.close();
}
return 0;
}

Related

file not opening via terminal using g++ file is in same directory

i made a program that processes a file with the name passed in by the user.
when compiling through an IDE i get the correect outputs, but when im compiling and running through the MacOS terminal using g++, the program doesnt catch the entered filename so im stuck in the while loop and the rest of the code wont run.
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
using namespace std;
double numrows(string name)
{
double index = 0;
string currentline;
fstream myFile;
myFile.open(name);
while(myFile)
{
getline(myFile, currentline);
index++;
if(myFile.eof())
{
myFile.clear();
myFile.seekg(0,ios::beg);
break;
}
}
return index;
}
double findaverage(double numrows, double sum)
{
return (sum/numrows);
}
bool checkifvalid(string victim)
{
for(auto &ch: victim)
if(!(isdigit(ch)))
{
return false;
}
return true;
}
int main()
{
string currentline, number,NaN;
double largest = 0.0;
int index = 0;
double validcount =0.0;
double firstcolsum = 0;
fstream myFile;
bool userinput = false;
string filename;
cout << "please input file name :";
cin >> filename;
myFile.open(filename);
while(!myFile)
{
cout << "file not found please try again.." ;
cin >> filename;
myFile.open(filename);
}
double size = numrows(filename);
while(myFile)
{
getline(myFile, currentline);
stringstream ss(currentline);
while(getline(ss, number, ','))
{
bool valid = checkifvalid(number); // checking if number is valid (in string)
if(valid == false)
{
NaN += number + ",";
}
else
{
double num = stoi(number);
if(index%2 == 0) //check if index even or odd if even then its first row, viceversa
{
firstcolsum += num;
validcount++;
}
else
{
if(num > largest)
largest = num;
}
}
index++;
}
if(myFile.eof())
break;
}
double average = findaverage(validcount, firstcolsum);
cout << fixed<< setprecision(4);
cout << "The average value of all numbers in the first column: " << average << endl;
cout<< setprecision(0);
cout << "The largest value of all numbers in the second column: " << largest<< endl;
cout << "The total number of rows in the file is: " << size << endl;
cout << "The invalid numbers are: " << NaN << endl;
}`
is my current code and it works via other IDE's but not g++
i tried making new folders and sources but nothing seems to be working.
Make sure you have navigated into the folder containing the source and input files using the 'cd' command, and that the name of the input file does not contain any spaces.

My Ifstream reference is not working although it did in similar previous function

I have a file I want to continue calling on in different functions in my program. It worked fine as a reference in the shiftText function but when I repeated the reference in the next function, all that returns is 0,
Can I get a small hint at something I am missing perhaps to make it behave this way? Thanks!
(PS there's definitely a lot of 'fat' in this that I have included for testing purposes only)
I will eventually return the value of "e" into the shiftText function if you were curious why that's there :)
#include <iostream>
#include <cmath>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void inputfile(ifstream &masterfile) // ask for file name
{
string filename;
cout << "Please enter the name and extension of your file " << endl;
cin >> filename;
masterfile.open(filename);
if (!masterfile)
{
cout << "warning: cannot open file" << endl;
exit(1);
}
}
int findShift(ifstream &file, int counter[]) // find most used char
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
counter[code]++;
}
int max, min;
int indexMax, indexMin;
max = counter[65];
indexMax = 65;
min = counter[65];
indexMin = 65;
for (int i = 66; i <= 122; i++)
{
if (counter[i] > max)
{
max = counter[i];
indexMax = i;
}
if (counter[i] < min)
{
min = counter[i];
indexMin = i;
}
}
cout << endl
<< "Most frequent was " << indexMax;
return indexMax;
}
void shiftText(ifstream &file) // this is where my program skips over my ifstream reference
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
}
}
char stopFlashing() // for sanity
{
char reply;
cout << endl
<< "Press q (or any other key) followed by 'Enter' to quit: ";
cin >> reply;
return 0;
}
int main()
{
int counter[256] = {0};
ifstream file;
inputfile(file);
int e = findShift(file, counter);
shiftText(file);
cout << endl << " " << file << " " << endl; // for testing, a zero is returned
stopFlashing();
}
In function findShift you loop over the file. In function shiftText you are trying to do the same. However, the file is already at its end. Before calling shiftText you should rewind the file by using seekg:
file.seekg(0, std::ios_base::beg)

Output stream not working without any error

I would like to make program that uses bubble sorting algorithm to sort some data from input program and write sorted values into output file - however everything seems fine, but the output file is empty...
I've tried to use a console as output but it didn't help. I know that there are functions for bubble sorting, but I'm quiet new in c++ topic and would like to gain some experience in it.
#include <iostream>
#include <fstream>
#include <string>
struct Datas
{
std::string day;
float value;
};
using namespace std;
int main ()
{
fstream file_in, file_out;
string name, line, data;
Datas current [7];
cout << "Input file name with data to open" << endl;
cin>>name;
file_in.open(name.c_str());
if (file_in.fail())
{
cout << "Unable to open file - try again" << endl;
// pause(TIME);
system ("CLS"); //Clears the console
main();
} else {
cout << "Input output file name to save sort datas" << endl;
cin>>name;
file_out.open(name.c_str());
if (file_out.fail())
{
cout << "Unable to open file - try again" << endl;
} else {
while (file_in.eof() == 0)
{
for (int pointer = 0; pointer < 7; pointer++)
{
file_in >> current[pointer].day >> current[pointer].value;
}
string tmp_day;
float tmp_val;
for (int current_val = 0; current_val < 7; current_val++)
{
if (current[current_val].value > current[current_val+1].value ||
current[current_val].value > current[current_val+2].value ||
current[current_val].value > current[current_val+3].value ||
current[current_val].value > current[current_val+4].value ||
current[current_val].value > current[current_val+5].value ||
current[current_val].value > current[current_val+6].value )
{
tmp_day = current[current_val+1].day;
tmp_val = current[current_val+1].value;
current[current_val].day = tmp_day;
current[current_val].value = tmp_val;
tmp_day = current[current_val].day;
tmp_val = current[current_val].value;
}
}
for (int stream = 0; stream < 7; stream++)
{
file_out << current[stream].day << '\t' << current[stream].value << endl;
}
}
file_in.close();
file_out.close();
return 0;
system("PAUSE"); //Keeps console window open after program execution
}
}
}

c++ get array string from text file

my text file was like
Jason Derulo
91 Western Road,xxxx,xxxx
1000
david beckham
91 Western Road,xxxx,xxxx
1000
i'm trying to get the data from a text file and save it into arrays however when i want to store the data from the text file into array it loop non-stop. what should i do ? the problem exiting in looping or the method i get the data from text file ?
code:
#include <iostream>
#include <fstream>
using namespace std;
typedef struct {
char name[30];
char address[50];
double balance;
} ACCOUNT;
//function prototype
void menu();
void read_data(ACCOUNT record[]);
int main() {
ACCOUNT record[31]; //Define array 'record' which have maximum size of 30
read_data(record);
}
//--------------------------------------------------------------------
void read_data(ACCOUNT record[]) {
ifstream openfile("list.txt"); //open text file
if (!openfile) {
cout << "Error opening input file\n";
return 0;
} else {
int loop = -1; //size of array
cout << "--------------Data From File--------------"<<endl;
while (!openfile.eof()) {
if (openfile.peek() == '\n')
openfile.ignore(256, '\n');
openfile.getline(record[loop].name, 30);
openfile.getline(record[loop].address, 50);
openfile >> record[loop].balance;
}
openfile.close(); //close text file
for (int i = 0; i <= loop + 1; i++) {
cout << "Account " << endl;
cout << "Name : " << record[i].name << endl;
cout << "Address : " << record[i].address << endl;
cout << "Balance : " << record[i].balance << endl;
}
}
}
Use ifstream::getline() instead of ifstream::eof() in tandem with >>. The following is an illustrative example, (and for simplicity I didn't check to see if the stream opened correctly).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define ARR_SIZE 31
typedef struct {
char name[30];
char address[50];
double balance;
} ACCOUNT;
int main() {
ACCOUNT temp, record[ARR_SIZE];
ifstream ifile("list.txt");
int i=0;
double d=0;
while(i < ARR_SIZE) {
ifile.getline(temp.name, 30, '\n');//use the size of the array
ifile.getline(temp.address, 50, '\n');//same here
//consume the newline still in the stream:
if((ifile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
for (int i=0; i < ARR_SIZE; i++) {
cout << record[i].name << "\n"
<< record[i].address << "\n"
<< record[i].balance << "\n\n";
}
return 0;
}
Another recommendation would be to use vectors for record array, and strings instead of char arrays.
REFERENCES:
Why does std::getline() skip input after a formatted extraction?

how to use strstr()?

i want to take data from file and store it in string array and and perform a search function with only few information like type"j" and the program able to look for data name which contain "j".
but my program cannot work.....
i am wondering am i using the strstr() correctly or not?
my text file :
Jason Derulo
5000
Martin Delux
8752
Justin Haber
51855
Alex Zander
52163
and
coding:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
//---------------------------------------------------------------------------------------------------------
typedef struct
{
char name[30],adv_srh_name[30];
double balance;
}ACCOUNT;
int main()
{
ACCOUNT record[31];
int choice,acc_amount=0;
ifstream openfile("list.txt"); //open text file
if (!openfile)
{
cout << "Error opening input file\n";
return 0;
}
else
{
ACCOUNT temp;
int i = 0;
double d = 0;
while (openfile)
{
openfile.getline(temp.name, 30, '\n');
//consume the newline still in the stream:
if ((openfile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
openfile.close(); //close text file
acc_amount = i;
}
cout << "Please enter a client name:";
fflush(stdin);
cin.getline(adv_srh_name, 30);
for (int j = 0; adv_srh_name[j] != NULL; j++)
adv_srh_name[j] = toupper(adv_srh_name[j]);
cout << adv_srh_name;
for (int a = 0; a < acc_amount; a++)
{
if ((strstr(record[a].name, adv_srh_name)) != NULL)
{
cout << "Name :" << record[a].name << "\n";
cout << "Balance :" << record[a].balance << "\n\n";
}
}
return 0;
}