ifstream giving me trouble - c++

im using fstream to get visual studio to read a file with about 100 lines of repeated info, just different values every line. Im using a count variable to keep track of how many times this is read, but it keeps saying 0. i know the file is being opened because i placed an If statement to check for me. and yes the file im reading from is also the location of my cpp file. If you could take a look and tell me what im missing i would appreciate it!
#include<iostream>
#include<iomanip>
#include<fstream>
#include<string>
using namespace std;
int main() {
//file variables
string date;
int rainIn, minTempF, maxTempF;
//variables
int count = 0;
double totalRain = 0;
double averageMinimumTemp = 0;
double averageMaximumTemp = 0;
double overallMaxTemp = 0;
double overallMinTemp = 0;
ifstream inFile("2014WeatherData.txt");
if (!inFile) {
cout << "Error: Input File Cannot Be Opened\n";
exit(EXIT_FAILURE);
}
//read file records
while (inFile >> date >> rainIn >> maxTempF >> minTempF) {
count++
}
cout << count << " Records read\n";
return 0;
}
im only in computer science 1, so im still learning any feedback will be very much appreciated!!
also here is a few lines from the txt document im trying to read from
20140101 0.00 69.08 31.10
20140102 0.00 42.98 25.16
20140103 0.00 51.98 25.16

The problem is that...
int rainIn, minTempF, maxTempF;
...creates integer variables, and you try to read floating point values into them. Change them to doubles. (You also need a semicolon after count++).

Related

Printing integers from a file using an array

I'm just beginning to learn C++ and I am having some trouble with a program. It's supposed to sort numbers from an external file. I've managed to successfully code the sorting algorithm, but I am having trouble working with the external file. I am just testing some things out in a separate program to gain an understanding of how things like ifstream work. I should be able to figure out how to implement it into my program once I gain a better understanding of how it works.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
int main() {
using namespace std;
int count;
ifstream InFile;
InFile.open ("unsorted.txt");
InFile >> count;
int numbers[count];
for(int a = 0; a < count; a++)
InFile >> numbers[a];
cout << numbers << endl;
}
Currently, the output for this is 0x7ffc246c98e0 I am not sure why this is the case I'm just attempting to print my file of integers. Could anyone help explain what I am doing wrong? I'd be very thankful.
When you do
cout << numbers << endl;
you print the pointer to the first element of the array.
You want
cout << numbers[a] << '\n';
to print the current element.
Furthermore, if that's all your program is doing, then you don't actually need the array. All you need is a single int variable:
int value;
for (int a = 0; a < count; ++a)
{
InFile >> value;
cout << value << '\n';
}
That also solve the problem with the variable-length array (since there isn't any).
If you intend to use count variable to count the file size or something, it is where your code goes wrong. You can't count the length of the file as like as you are trying.
while( getline ( InFile, line ) )
{
count += line.length();
}
Maybe, try like this!!!
If you use
InFile>>count;
it would try to store all the string from InFile stream to count, which is not intended.

Reading a text file into a struct array c++

This is for a homework assignment, but what I am presenting is a small test program for a chunk of my assignment.
Starting out, I am to have a list of songs in file "songs.txt". My current file looks like this.
Maneater;4;32
Whip It;2;41
Wake Me Up Before You Go-Go;3;45
The file simply contains a song title, and the duration in minutes and seconds, with the title, minutes, and seconds separated by semicolons. The full file is supposed to contain the Artists and Album as well, all separated by semicolons. Anyways, the code.
#include<iostream>
#include<cstring>
#include<fstream>
#include<cstdlib>
using namespace std;
const int CAP = 100;
const int MAXCHAR = 101;
struct songInfo
{
char title[CAP];
char durMin[CAP];
char durSec[CAP];
};
void getData(songInfo Song[], int listSize, int charSize);
int main()
{
string fileName;
songInfo Song[CAP];
ifstream inFile;
cout << "What is the file location?: ";
cin >> fileName;
inFile.open(fileName.c_str());
if (inFile.fail())
{
cout << "Cannot open file " << fileName << endl;
exit(1);
}
getData(Song, CAP, MAXCHAR);
for (int i=0;i<CAP;i++)
{
cout << Song[i].title << " - "
<< Song[i].durMin << ":"
<< Song[i].durSec << endl;
}
cout << "Press any button to continue..." << endl;
cin.get(); cin.get();
return 0;
}
void getData(songInfo Song[], int listSize, int charSize)
{
for (int i = 0; i < listSize; i++)
{
cin.get(Song[i].title, charSize, ';');
cin.get(Song[i].durMin, charSize, ';');
cin.get(Song[i].durSec, charSize, '\n');
i++;
cin.ignore();
}
}
The program compiles correctly without incident, but the output is not what I want it to be. What should happen:
Test.cpp opens songs.txt
Read the first char array into Song[i].title, delimited by ';'
Read the second char into Song[i].durMin, delimited by ';'
Read the third char into Song[i].durSec, delimited by newline
After compiling the code and running it, I get this as my output:
~/project2Test> ./test
What is the file location?: songs.txt
The program then hangs here and I have to ctrl+C out
First, what am I doing wrong?
Second, how do I go about fixing what I screwed up?
Also, as a note for class rules, I am not allowed to use any strings except for the filename. Other than that, all words must be chars.
A debugger is definitely a good thing to use for a problem like this.
Your hanging problem is occurring because in your get_data function you are using cin.get instructing your program to get input from the standard input file. You intended to use the file you defined, "inFile" not the standard input cin.
As an aside it is not clear to me why you are incrementing i twice per iteration of the for loop.
Use inFile.get() instead of cin. You need to pass inFile to the function first.
Put a print statement in the for loop to see what is happening.. A future issue that might crop up is that if you are on a Windows machine and have \r\n line endings. Unix uses \n, Windows uses \r\n

Trying to store data from text file into vector of objects

I am trying to get a few lines from a text file to store into a class, Item, and using vectors. However, when I read from the file into the program, nothing is stored.
Here is my main:
#include <vector>
#include <fstream>
#include <iostream>
#include "Item.h"
using namespace std;
void readFile(vector<Item>&);
int main()
{
vector<Item> items;
readFile(items);
int size = items.size();
for (int index = 0; index < size; index++)
{
cout << items[index].getName() << endl;
}
}
This is the function in question:
void readFile(vector<Item>& vecItems, int lines)
{
ifstream inventory;
inventory.open("inventory.txt");
string itemName;
int itemDept, itemPrice, itemQuan, itemShort, itemSurplus;
string line;
if (inventory.fail())
{
cout << "ERROR NO FILE FOUND (inventory.txt)\n";
exit(1);
}
while (inventory >> itemName >> itemDept >> itemPrice >> itemQuan >> itemShort >> itemSurplus)
{
Item temp(itemName, itemDept, itemPrice, itemQuan, itemShort, itemSurplus);
vecItems.push_back(temp);
}
inventory.close();
}
I've tried calling
temp.setName(itemName)
etc etc
individually but it still does not hold in the vector. Nothing outputs in main and the debugger says size = 0. Any help is appreciated
EDIT: This is the file format
vitamins 1 15.99 1105 500 1000
shampoo 2 6.99 298 300 500
Your problem is you have a bad read. item_price is declared as an int but the price in the file is a floating point number. When you try to read in item_price it capture everything up to the . and then stops reading. On the next read operation for itemQuan it gets the . and fails as . is not a valid int. Since the read fails you never enter the while loop body which means you never create any objects.
Change item_price to a float, double or std::string to fix this.

ifstream is failing to open file

Here is my code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
ifstream stream;
stream.open("scores.txt");
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failed\n"<<strerror(errno)<<endl;
for(int i=1;i<5;i++)
{
stream>>scores[i];
stream>>names[i];
cout<<i<<endl;
}
cout<<scores[2]<<endl;
stream.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
It get garbage output for scores[2] because stream.open("scores.txt") fails to open a file.
strerror(errno) gives me "No error".
I've checked to see if my file is really called "scores.txt.txt". It is not. I've also tried moving my file to "C:\scores.txt". I've tried using the full address. I've tried deleting it and re-creating it. I've tried other things too that I cannot remember. ![enter image description here][1]I've been trying for hours to fix this and I'm desperate. I'd be grateful if anyone could help me fix this.
void gethighscores is a function that I plan to use later.
The input file looks like this:
Ronaldo
10400
Didier
9800
Pele
12300
Kaka
8400
Cristiano
8000
The output of the program looks like this
It failed
No error
1
2
3
4
-858993460
Press any key to continue . . .
I'm running this in Microsoft Visual Studio Express 2012 for Windows Desktop
My operating system is Windows 7 ultimate 64 bit.
when using the "\" to define a path use two instead of one
C:\ \scores.txt
try this:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getHighScores(int scores[], string names[]);
int main()
{
string filename = "scores.txt"; // could come from command line.
ifstream fin(filename.c_str());
if (!fin.is_open())
{
cout << "Could not open file: " << filename << endl;
return 1;
}
int scores[32];
string names[32];
int iter = 0;
while (fin >> names[iter] >> scores[iter])
{
if (++iter >= 32 )
{
break;
}
cout << iter << endl;
}
if (iter >= 2)
{
cout << scores[2] << endl;
}
fin.close();
return 0;
}
void getHighScores(int scores[], string names[])
{
}
Had me stumped for a bit. Your C++ code is reading scores and names in the opposite order from your input text. The first line of text in the input file is Ronaldo, but your first operator>> is to score[0] (an int). This causes the failbit to be set, and so fail() returns true. It also explains why you end up getting garbage for the destination array elements.
Reverse the order of the scores/names in either the scores.txt file or your C++ parsing code (but not both!) and you should be good to go.
The reason it fails is this:
int scores[32];
string names[32];
stream>>scores[0];
stream>>names[0];
if(stream.fail())
cout<<"It failed\n"<<strerror(errno)<<endl;
By default, scores[0] and names[0] don't have any set value and it tries to assign them to the file, which causes it to fail. If you try commenting those two lines:
stream>>scores[0];
stream>>names[0];
You'll see that it no longer fails and works fine.

C++ - Using stringstream object to read strings and integers from a sentence in an external txt file

I tried to retrieve the integers from a txt file and adding them up to get the total. I did this using stringstream class. The string of the text is:- 100 90 80 70 60. The code to extract the integers and add them is as follows:-
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
stringstream sstr;
string from_file;
int grade;
int total = 0;
getline(inFile,from_file);
sstr<<from_file;
while(sstr
{
sstr>>grade;
cout<<grade<<endl;
total+=grade;
}
cout<<total<<endl;
inFile.close();
return 0;
}
This code works fine. After this, I modify the string in the file as 'the grades you scored are 100 90 80 70 60`. Now, if try to run the above code, I get the output as:-
0
0
0
0
0
0
Can you please help me and tell me how to calculate the total in the latter case ? Also, here I know the number of integers in the files. What about the case when I don't know the number of grades in the file?
Because "the grades you scored are " is the head part of your stringstream.
You cannot get read an int from it. It'll just give you a 0
You may read to some string as "Entry" and parse the Entry by writing some functions.
I'll be answering the second part of the question i.e. reading inputs without knowing the total number of inputs:-
#include<iostream>
#include<fstream>
#include<sstream>
using namespace std;
int main(void)
{
ifstream inFile("C:\\computer_programs\\cpp_programs\\exp6.txt",ios::in);
string data;
int grades,total=0;
getline(inFile,data);
stringstream sstr;
sstr<<data;
while(true)
{
sstr>>grades;
if(!sstr)
break;
cout<<grades<<endl;
total+=grades;
}
cout<<total<<endl;
return 0;
}