Garbage value on reading from a file using getline - c++

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

Related

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

Cannot find input file [duplicate]

This question already has an answer here:
Cannot open input file
(1 answer)
Closed 7 years ago.
I am trying to create a program that asks the user for the name of a file, then opens the file, adds the sum of all the integers listed on the file, then writes that sum on an output file.
After writing my code and saving the testfile1.txt into the same folder as the program, the program keeps giving me the: "could not access testfile1" (message I output to notify myself that it is unable to open the testfile1.txt).
Here is what I have so far (skipped the lines with description blocks):
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream inputFile;
ofstream outputFile;
string testfile1;
string sum;
int total = 0;
int num;
cout << "Please input name of file." << endl;
cin >> testfile1;
cin.get();
inputFile.open(testfile1.c_str());
if (inputFile.fail()) {
inputFile.clear();
cout << "could not access testfile1" << endl;
return(1);
}
while (!inputFile.eof()) {
inputFile >> num;
total = total + num;
inputFile.close();
}
outputFile.open(sum.c_str());
outputFile << total << endl;
outputFile.close();
if (outputFile.fail()) {
cout << "could not access file." << endl;
return 1;
}
return 0;
}
Question:
How can I make this program find and open the testfile1.txt?
Note:
I am pretty sure that when prompted for the file name, I did not misspell.
Here are few remarks that will help you figure out the possible problem:
1.You could reduce some lines of code by attaching your streams to a file during definition, instead of defining them and then use open, like so:
ifstream inputFile(testfile1.c_str());
2.To check if a file is open (and handle if it couldn't):
if (!inputFile) error ("Can't open input file: ", testfile1);
and:
if (!outputFile) error ("Can't open output file: ", sum);
right after the definition.
3.All open files are implicitly closed at the end of the program (or a function that contains them), so there is no need to explicitly close() them.
4.To read the contents of the input file and sum them:
int sum = 0;
string line;
// read a line
while (getline(inputFile, line)) {
stringstream ss(line);
// assuming you are reading integers separated by white space
int num = 0;
// extract each number on the line
while (ss >> num) total += num;
// reset line
line.erase();
}
Note: test and modify your code according to your specific needs. A side note: you could probably omit: cin.get(); in your code.
use getline (std::cin,name);
for input name
and use proper function of ostream for reading and writing.
you'r getting input wrong at line 21 and line 22

Combining three text files into one text file forming a sentence C++

I am trying to create a program in C++ using Microsoft Visual Studio 2013. The main purpose of this program is to read three different files(headlines1,headlines2, and headlines3) and put them all together to form a single file and creating a sentence within that output file. I have figured out a function that I could use, but this function only reads and prints the 3 files out onto the console window. When I try to change the cout statement into an outfile, my outfile that I created is blank... I don't know what to do or how to structure the code.
#include<fstream>
#include<iostream>
#include<cstdlib>
using namespace std;
void readingFile(string[], ifstream &); //Funtion Prototype
int main()
{
string header1[50], header2[50], header3[50]; //Declaring array with 50 elements
int size1, size2, size3;
ifstream Fin, Fin2, Fin3;
ofstream Fout;
Fin.open("Headlines1.txt"); //Reading from these 3 files.
Fin2.open("Headlines2.txt");
Fin3.open("Headlines3.txt");
if (!Fin || !Fin2 || !Fin3) //Checking for unsuccessful open
{
cout << "Input file opening failed.\n";
cin.ignore();
return 1;
}
Fout.open("testingHeadlines.txt"); //Used for unsuccessful opening output
if (!Fout)
{
cout << "Output file opening failed.\n";
cin.ignore();
return 2;
}
cout << "Building.... Editing....\n" << endl;
cin.ignore();
cout << "Headlines file 1 below:\n" << endl;
readingFile(header1, Fin); //Function call
cout << endl << endl;
cout << "Headlines file 2 below:\n" << endl;
readingFile(header2, Fin2); //Function call
cout << endl << endl;
cout << "Headlines file 3 below:\n" << endl;
readingFile(header3, Fin3); //Function call
cout << endl << endl;
cin.ignore();
return 0;
}
//the function 'readingFile'
//Pre-conditions: Reads the contents from the files of Headlines1,2,and 3
//Post-conditions: Prints out the contents.
void readingFile(string[], ifstream &infile)
{
char next;
infile.get(next);
while (!infile.eof()) //Reading until EndOfFile
{
cout << next; //Problem is here?? I would think.
infile.get(next);
}
}
I'm just not certain if where I said the "Problem is here??" is where the problem is at. Every time I change the cout to outfile(I know, I have to change the parameters within the function header) once doing that I open the outfile and the file is blank.
All the files contain random words/phrases and when put together they will make a sentence. For ex. Headlines1 contains '***Queen Jennifer*'** Headlines2 contains '***has brain surgery*'** Headlines3 contains '***after eating 30 jalapenos.*'** and When put together it should read 'Queen Jennifer has brain surgery after eating 30 jalapenos.' but the files contain more words/ phrases that what I just listed in my example.
When I run the program above I am able to read all three Headline files, but they are printed in up to down form. For example, my output on my console screen would be:
Queen
Jennifer
has brain surgery
after eating 30 jalapenos
Problem:
Getting my headlines to read from left to right.
Getting them into a output file instead of the console screen.
Help Please.
You could replace this...
void readingFile(string[], ifstream &infile)
{
char next;
infile.get(next);
while (!infile.eof()) //Reading until EndOfFile
{
cout << next; //Problem is here?? I would think.
infile.get(next);
}
}
...and the calls there-to, such as...
readingFile(header1, Fin);
...with this...
void readingFile(ifstream& infile, ofstream& fout)
{
char next;
while (infile.get(next)) //Reading until EndOfFile or error
if (next != '\n') // if not newline
fout << next; // stream to file
}
...and calls ala...
readingFile(Fin, Fout);
That way readingFile is told where to write the output, and filters out the newline characters that were causing the output to appear on different lines.
This should do the trick.
#include <fstream>
#include <string>
int main() {
// Open the three files.
std::ifstream file_1("Headlines1.txt");
std::ifstream file_2("Headlines2.txt");
std::ifstream file_3("Headlines3.txt");
// Combine into one string.
std::string content;
content += std::string(std::istreambuf_iterator<char>(file_1),
std::istreambuf_iterator<char>());
content += std::string(std::istreambuf_iterator<char>(file_2),
std::istreambuf_iterator<char>());
content += std::string(std::istreambuf_iterator<char>(file_3),
std::istreambuf_iterator<char>());
// Output the string into a single file.
std::ofstream output_file("testingHeadlines.txt");
output_file << content;
}
I'm not sure what you're wanting to do about spacing between files, but that shouldn't be too hard for you to fine-tune this code for.
one possible thing why your ouput is like this is that std::ifstream::get() that you used in infile.get(next) is a non-formatted reading method which means it will not skip white spaces and newline character \n by default. so you need to check if next value is a newline like this:
if(next == '\n') continue ;
before passing it to cout << next. Thus you will skip printing a newline in your console screen.

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.

adding a newline to file in C++

Can any body help me with this simple thing in file handling?
The following is my code:
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ofstream savefile("anish.txt");
savefile<<"hi this is first program i writer" <<"\n this is an experiment";
savefile.close();
return 0 ;
}
It is running successfully now, I want to format the output of the text file according to my way.
I have:
hi this is first program i writer this is an experiment
How can I make my output file look like the following:
hi this is first program
I writer this is an experiment
What should I do to format the output in that way ?
#include <fstream>
using namespace std;
int main(){
fstream file;
file.open("source\\file.ext",ios::out|ios::binary);
file << "Line 1 goes here \n\n line 2 goes here";
// or
file << "Line 1";
file << endl << endl;
file << "Line 2";
file.close();
}
Again, hopefully this is what you want =)
First, you need to open the stream to write to a file:
ofstream file; // out file stream
file.open("anish.txt");
After that, you can write to the file using the << operator:
file << "hi this is first program i writer";
Also, use std::endl instead of \n:
file << "hi this is first program i writer" << endl << "this is an experiment";
// Editor: MS visual studio 2019
// file name in the same directory where c++ project is created
// is polt ( a text file , .txt)
//polynomial1 and polynomial2 were already written
//I just wrote the result manually to show how to write data in file
// in new line after the old/already data
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main()
{
fstream file;
file.open("poly.txt", ios::out | ios::app);
if (!file) {
cout << "File does not exist\n";
}
else
{
cout << "Writing\n";
file << "\nResult: 4x4 + 6x3 + 56x2 + 33x1 + 3x0";
}
system("pause");
return 0;
}
**OUTPUT:** after running the data in the file would be
polynomial1: 2x3 + 56x2-1x1+3x0
polynomial2: 4x4+4x3+34x1+x0
Result: 4x4 + 6x3 + 56x2 + 33x1 + 3x0
The code is contributed by Zia Khan
use ios_base::app instead (adding lines instead of overwriting):
#include<fstream>
using namespace std;
int main()
{
ofstream savefile("anish.txt", ios_base::app);
savefile<<"hi this is first program i writer" <<"\n this is an experiment";
savefile.close();
return 0 ;
}