Reading text file c++ (not able to display other lines) - c++

char fname[20];
char lname[20];
int grade[10];
double avg=0.00;
fstream infile("C:\\Users\\Hady Zn\\Desktop\\hady.txt", ios::in);
fstream outfile("C:\\Users\\Hady Zn\\Desktop\\hady1.txt", ios::out);
while(infile>>fname>>lname)
{
outfile<<fname<<" "<<lname<<" ";
for(int i=0; i<10; i++)
grade[i]=0;
for(int i=0; i<10; i++)
{
infile>>grade[i];
if(grade[i]>=0 && grade[i]<=100)
{
outfile<<grade[i]<<" ";
avg+=grade[i];
}
}
outfile<<avg/10.00<<endl;
avg=0.00;
}
So the question is that i need to read from a text file a last name(space) first name(space) then 10 quiz grades(space between each grade) and write the same data into an output file with the average of 10 quizzes at each end of a line. The problem that im facing is that if i had less than 10 quizzes on one line it will not display the remaining lines.(I want it to still give me the average of the grades given considering for example if i was given 7 grades 3 will be zeros) I tried solving it but it just won't work. Any ideas that can solve this? Please help. Thank you

In order to perform such checks, it's better to read the text from the input file line by line and process each line to extract the data.
string line
while ( getline(infile, line) )
{
istringstream sstream(line);
sstream >> fname >> lname;
if (!sstream )
{
continue;
}
outfile<<fname<<" "<<lname<<" ";
for(int i=0; i<10; i++)
{
grade[i]=0;
sstream>>grade[i];
if ( !sstream )
{
break;
}
if(grade[i]>=0 && grade[i]<=100)
{
outfile<<grade[i]<<" ";
avg+=grade[i];
}
}
}
Update, in response to comment by OP:
You can avoid reading the input file line by line and processing each line. Here's my suggested changes to the loop.
while(infile>>fname>>lname)
{
outfile<<fname<<" "<<lname<<" ";
for(int i=0; i<10; i++)
{
grade[i]=0;
infile>>grade[i];
if ( !infile )
{
infile.clear();
break;
}
if(grade[i]>=0 && grade[i]<=100)
{
outfile<<grade[i]<<" ";
avg+=grade[i];
}
}
outfile<<avg/10.00<<endl;
avg=0.00;
}

Related

Parse (split) a txt file with a string and int in c++

im a Student and new to this site. I want to split my txt file with my highscore data back to my Highscore List.
The txt file stores my Highscore like name:score
My parsing is not working and i dont know why?
I just want to split it to name and score again and then put it in my HighscoreList.
If you have any question about the code just ask :)
#include "highscore.h"
highscore::highscore(){
}
struct highscore::Player{
string spielerName;
int score;
};
void highscore::writeHighscore(string name, int score ,int playerNumberx){
Player HighscoreListe[100];
for(int i=0;i<=99;i++){
HighscoreListe[i].score = {0};
}
for(int i=0;i<=99;i++){
HighscoreListe[i].spielerName = "leer";
}
HighscoreListe[playerNumberx].spielerName = name;
HighscoreListe[playerNumberx].score = score;
int i, j,temp;
string temp1;
ifstream myfile("scores.txt");
string line;
//heres the point where i need help!!
if (myfile.is_open()){
int z=0;
while(getline(myfile, line)){
string name1;
string score1;
int d = 20;
while(line[z] != ':'){
name1 += line[z];
z++;
}
z = z+2;
while(line[z] != '\0'){
score1 += line[z];
z++;
}
HighscoreListe[d].spielerName = name;
HighscoreListe[d].score = score;
d++;
}
myfile.close();
}else cout << "Unable to open file" << endl;
for(i = 0; i<100; i++) {
for(j = i+1; j<100; j++)
{
if(HighscoreListe[j].score < HighscoreListe[i].score) {
temp = HighscoreListe[i].score;
temp1 = HighscoreListe[i].spielerName;
HighscoreListe[i].score = HighscoreListe[j].score;
HighscoreListe[i].spielerName = HighscoreListe[j].spielerName;
HighscoreListe[j].score = temp;
HighscoreListe[j].spielerName = temp1;
}
}
}
ofstream myfilex("scores.txt");
if (myfilex.is_open()){
for(int i = 99;i>89;i--){
myfilex << HighscoreListe[i].spielerName << ":" << HighscoreListe[i].score<<endl;
}
myfilex.close();
}
else cout << "Unable to open file" << endl;
}
void highscore::readHighscore(){
string line;
ifstream myfile("scores.txt");
if (myfile.is_open()){
while(getline(myfile, line)){
cout << line << endl;
}
}
else cout << "Unable to open file" << endl;
}
Make a >> overload for highscore::Player.
In the >> overload
Use std::getline to read a line from the input stream.
Create a std::istringstream out of the line.
Use std::getline to read up to the : from the istringstream into a local string name;.
Use another std::getline to read the rest of the line into a string.
Convert the string into an int with std::stoi and store into a local int score;. Make sure you provide a pos argument.
Ensure that the entire string was converted by comparting the pos argument with the string's length.
If nothing went wrong, store name and score into the highscore::Player passed by the caller. Otherwise, set the failbit on the input stream with setstate
return the input stream.
Now the reading code should be something simple like
int scorecount = 0;
while (myfile >> HighscoreListe[scorecount])
{
scorecount++;
}

print certain number of lines from a file in C++

i am trying to print 10 lines from a text file, and print another 10 based on user input or stop. My code print 10 lines but the first line is blank each time.
cin>>input;
ifstream file("midterm.txt");
while(input != sentinel && file >> output ) {
for(int i = 0; i < 10; i++) {
getline(file, output);
cout<<output<<endl;
}
cout<<"\nEnter any key to continue reading, enter # to stop"<<endl;
cin>>input;
}
file.close();
cout<<"File End";
return 0;
In your code, you should add ios::ate to make the lines working and you should also show what type are the used variables. Try that:
string input;
string sentinel = "#";
string output;
cin>>input;
ifstream file("midterm.txt",ios::ate);
while(input != sentinel && file >> output ) {
for(int i = 0; i < 10; i++) {
getline(file, output);
cout<<output<<endl;
}
cout<<"\nEnter any key to continue reading, enter # to stop"<<endl;
cin>>input;
}
file.close();
cout<<"File End";
return 0;

How to get a specific word from a text file in c++?

I am trying to get a specific word from a .txt file content. Let say, I have a .txt file:
cottage.txt
1 [1] Cottage1 1000 01-10-2019 Free
2 [2] vottage2 2000 01-20-2019 Free
I want to get the word 1000 when I select the line with an ID of (1) or get the word 2000 with an ID of (2) depending on the user input.
My Code: - I know this is incomplete but I just to show what I have tried so far.
string GetWord(string filename)
{
string word;
string selectline;
ifstream fin;
fin.open(filename);
cout << "Select which line to get a word from: "; //select line
cin >> selectline;
//some code here......
temp.close();
fin.close();
return word;
}
If the format of every line in the text file is same, then you can try this code-
string GetWord(string filename)
{
string word, line;
int selectline;
ifstream fin(filename.c_str());
cout << "Select which line to get a word from: "; //select line
cin >> selectline;
int i = 1;
while (getline(fin, line))
{
if(i == selectline){
istringstream ss(line);
for (int j=0; j<4; j++){
ss >> word;
}
break;
}
i++;
}
return word;
}
Please let me know if you still have the problem :)

How to read a table from .txt file to C++

I want to read a matrix from a file and use it in my program. but when I output the results, it shows that it is not reading correctly.
Here is the code:
#define I 5
#define J 5
#define P 2
int i,j,k; //for loops
int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];
inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}
for(i=0; i<I; i++)
for(j=0; j<J; j++)
inFile >> C[i][j];
outFile.open("results.txt");
outFile<< "C" <<endl;
for(i=0;i<I;i++)
{
for(j=0;j<J;j++)
outFile<< C[i][j];
outFile<< endl;
}
inFile.close();
outFile.close();
return 0;
}
C is a matrix of integer values 2 3 5... but what I get is
316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061
You should output a whitespace after each number, otherwise they will be all glued together.
outFile<< C[i][j] << " ";
You also should check your input for validity. Not showing it here (you already know how to check if (! inFile)).
I suspect that you are having problems with new lines, below modification will ignore new line character after reading each line:
for(i=0; i<I; i++) {
for(j=0; j<J; j++)
inFile >> C[i][j];
inFile.ignore(); /// <<<--------
}
It seems you are writing uninitialized variables to your output file, leading to undefined behavior.
I suspect your C.txt file does not contain the 5x5 matrix your program is looking for.
You should add a simple error check, e.g.:
for(i=0; i<I; i++)
for(j=0; j<J; j++)
if (!(inFile >> C[i][j])) { /* something's wrong here */ }

Read file from txt

I ve got a txt file with double matrix 50x8. The first two lines contains the array size
50
8
the 50x8 matrix. When i trid to read this file with the above code:
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream infile;
infile.open("C:/Users/zenitis/Desktop/BTHAI_2.3b-src/BTHAI/txtFiles/W1.txt");
double events[50][8];
while (!infile.eof())
{
for(int j=0;j<50;j++)
{
for(int k=0; k<8;k++)
{
infile >> events[j][k];
// infile.get(c
}
}
} //end while
infile.close();
for(int i = 0; i<50; i++){
for(int l=0; l<8; l++){
cout << events[i][l] << " ";
}
cout << "\n";
}
cout << events[0][0];
system("pause");
return 0;
}
Firstly when i print the results the first two elements of the events matrix are the last two of the file. Secondly any idea how to read just the two first elements which is in fact the size of the matrix????
You read the number of rows and columns like this:
int R, C;
infile >> R;
infile >> C;
You do it before the nested loops that read the rest of the file. Then you use the numbers from the file as your end-of-loop targets, rather than hard-coding 50 and 8.