ifstream is failing to open file - c++

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.

Related

c++ text file redirection getline infinite loop

So I'm having an issue where I am reading in a text file using cin. Here is a basic idea of my code:
while(getline(cin,line) {
cout << line << endl;
}
//Do some task
return 0;
The problem I'm running into is that the loop will not terminate and //Do some task will never run. The only solution that I've found is to look directly at the text file, see how many lines of text there are, and hard code a conditional to break out of it. So say I have a text file with 5 lines and an variable int row. Then I would do something like this:
while(getline(cin,line) {
cout << line << endl;
if(row == 5) {
break;
}
//Do some task
return 0;
I tried googling but I can't seem to find an answer anywhere. Any ideas? And also only libraries I'm allowed to use is iostream.
You can use rdbuf to redirect your cin output
Following Link will help you.
http://www.cplusplus.com/reference/ios/ios/rdbuf/
The following code block should solve your issue:
Credit goes to the author: kevinchkin
http://www.cplusplus.com/forum/beginner/8388/
#include<iostream>
#include<fstream>
using namespace std;
int main() {
ifstream myReadFile;
myReadFile.open("text.txt");
char output[100];
if (myReadFile.is_open()) {
while (!myReadFile.eof()) {
myReadFile >> output;
cout<<output;
}
}
myReadFile.close();
return 0;
}
This is a basic template for reading from a .txt file. I also can not think of any reason why you should not be able to use more than just iostream. They make the other libraries because iostream isn't the best way to go about it.
Most(if not all) Teachers/Professors I have had like it when students go above and beyond what the class is studying, and try to learn more.
If you need additional help, take a look at: http://www.cplusplus.com/doc/tutorial/files/

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

ifstream giving me trouble

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++).

Garbage value on reading from a file using getline

I am writing a small program to just get the lines from a srt file in a specific format. However I am getting a garbage value in the very first (and only that) read I do using getline. Can someone point out why am I getting this abnormal behaviour?
//Small program to get the text from the srt files.
#include<iostream>
#include<string>
#include<fstream>
#include<algorithm>
#include<vector>
#include<sstream>
#include<conio.h>
using namespace std;
void srtToTranscript(ifstream* iFile, ofstream *oFile);
int main(){
std::string file_name;
std::string transcript;
cout << "Enter srt file name (without extension)";
cin >> file_name;
ifstream iFile;
ofstream oFile;
iFile.clear();
iFile.open("data\\" + file_name+".srt");
oFile.open("data\\" + file_name + "_result.txt");
srtToTranscript(&iFile,&oFile);
cout << "Conversion done. Check in the same folder";
cout << "Press a key to exit... ";
while (!_kbhit());
char dummy = _getch();
return 0;
}
void srtToTranscript(ifstream* iFile, ofstream* oFile)
{
int i = 1;
std:string line;
for (; getline(*iFile, line);)
{
cout << line << endl;
cout << to_string(i) << endl;
if (line.compare(to_string(i)) == 0){
getline(*iFile, line);
i++;
continue;
}
*oFile << line + ",\n";
}
oFile->close();
}
appended is a sample of the file I am reading from:
1
00:00:00,000 --> 00:00:12,000
Translator: Thu-Huong Ha
2
00:00:12,038 --> 00:00:15,012
Over the last two decades, India has become
The problem is your ifile is not being opened successfully.
I'm seeing #include <conio.h> in your include list so I assume that you are working on Visual Studio? If you have use the default directory structure when setting up Visual Studio, then say that you have a project named: "Foo" Your .srt file needs to go here:
.../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo.srt
When I correctly placed the file there and at the prompt I entered:
Foo
I got this output in: ".../Documents/Visual Studio 20##/Projects/Foo/Foo/data/Foo_result.txt":
00:00:00,000 --> 00:00:12,000,
,
Translator: Thu-Huong Ha,
,
00:00:12,038 --> 00:00:15,012,
,
Over the last two decades, India has become,
One thing I'd make sure of is that your line declaration in srtToTranscript is defined:
string line
Not:
std:string line

mixing fstream streams issue even when closed streams

I am having problems with the code bellow.
It can write fine if i kill the read section.
It can read fine if i kill the write section and the file has already been written.
The 2 don't like each other. It is like the write stream is not closed... though it should be.
What is wrong?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using namespace System;
int main(array<System::String ^> ^args)
{
string a[5];
a[0]= "this is a sentence.";
a[1]= "that";
a[2]= "here";
a[3]= "there";
a[4]= "why";
a[5]= "who";
//Write some stuff to a file
ofstream outFile("data.txt"); //create out stream
if (outFile.is_open()){ //ensure stream exists
for (int i=0; i< 5; i++){
if(! (outFile << a[i] << endl)){ //write row of stuff
cout << "Error durring writting line" << endl; //ensure write was successfull
exit(1);
}
}
outFile.close();
}
//Read the stuff back from the file
if(!outFile.is_open()){ //Only READ if WRITE STREAM was closed.
string sTemp; //temporary string buffer
int j=0; //count number of lines in txt file
ifstream inFile("data.txt");
if (inFile.is_open()){
while (!inFile.eof()){
if(! (getline(inFile, sTemp)) ){ //read line into garbage variable, and ensure read of line was
if(!inFile.eof()){ //successfull accounting for eof fail condition.
cout << "Error durring reading line" << endl;
exit(1);
}
}
cout << sTemp << endl; //display line on monitor.
j++;
}
inFile.close();
}
cout << (j -1) << endl; //Print number lines, minus eof line.
}
return 0;
}
You have a memory overwrite.
You have six strings, but dimension only for five strings
string a[5];
a[0]= "this is a sentence.";
a[1]= "that";
a[2]= "here";
a[3]= "there";
a[4]= "why";
a[5]= "who";
this can cause the rest of your program have unexpected behavior.
G... bows head in shame. Was playing with file streams and wasn't paying attention to the array initializations that i rushed through.
What is interesting is that MS VS 2005 did not complain about the array value assignment a[5]= "who". It let me get away with it. So I didn't even consider that durring debugging. I can kind of see why that is ok... I wrote it out of bounds in the next contiguous spot in memory and the MS compiler let me get away with it. As far as I remember Linux does complain about this type of error. No?
Thinking it was the read file back section that was wrong i commented out all of the read section except the line ifstream inFile("data.txt"). This cause the app to crash, leading me to think the write stream was somehow not closed. I take it that the
ifstream inFile("data.txt") line alone has little to do with the array in question when the rest of the read section is commented out. Yet that is what caused it to crash in VS 2005.
At any rate, thanks!
Works fine.