C++ programming I/O - c++

I am trying to take input from a text file containing 1000 records.
10
1 100
2 101
3 123
4 124
.
.
.
1000 1234
I am using the code below to take the input in three variables d=10 (first line of the text file, a contains all the numbers in first column and b contains all the numbers in second column.
The problem I am facing with this code is it takes the last half of the file as input the first half is ignored.
output:
500 3211
501 3212
502 22121
.
.
.
1000 1234
char fileName[20];
cout << "Enter input test file name: ";
cin >> fileName;
ifstream readFile; //object of input file stream
readFile.open(fileName); //open a file
//Check for an error
if (readFile.fail())
{
cerr << "Error Opening File" << endl;
}
string c, d,a,b;
getline(readFile, c);
for (int i=0; i<1000;i++)
{
getline(readFile, readLine);
istringstream split(readLine);
getline(split, a);
getline(split, b);
cout <<serverNum<<" "<<a<<" "<<b<<endl;
}
can someone suggest me why am I facing this

A better way would be this:
#include <iostream> // std::cout, std::endl
#include <fstream> // std::ifstream
using namespace std;
int main()
{
// open your file
ifstream input_file("test.txt");
// create variables for your numbers
int first_num, left_num, right_num;
// determine the first number in your file
input_file >> first_num;
// while there is a number on the left, put that number into left_num
while(input_file >> left_num)
{
// put the corresponding right number into right_num
input_file >> right_num;
// now you can work with them
cout << left_num << ' ' << right_num << endl;
}
// close the file
input_file.close();
return 0;
}
Edit:
#Syed the problem could be that your command line doesn't have enough buffering and just overwrites your previous 500 lines. Just go to your cmd, click the top left corner, go to settings, layout, and increase the buffer. The code works, it must be your console.
Also since you answered with a list containing floats, you might want to consider changing left_num and right_num from int to float or double.

Related

How do I read data from an input file using ifstream correctly?

I've already done multiple searches on this issue. I'm just getting back to programming and I'm trying to create a simple code just to get started.
I'm currently using g++ to compile my files. I am using gedit to type my code and input file.
Basically I want to read data from my input file (list of separate integers), find the total number of integers in the text file, then save them into an array.
The following is a HEADER file to be used in my main file.
//Make program to read data from in_2.txt then add them and print to output file out_2.txt
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include <iomanip>
std::ofstream outputfile("out_2.txt", std::ios::out);
class TEST_ADD{
public:
TEST_ADD(void); //constructor. Will use an unknown input file so nothing to do
void INPUTREAD(char *); // Read the data from the input file. Ex. //b.INPUTREAD ("in.2")
void ADD(void); //Will perform the actual summation and store value into int add
void PRINT(void); // Print the numbers being summed, along with it's sum into out.2
private:
int add; //will store the sum of the numbers
int n; //will keep track of total number of entries
int A[20]; //used to store the number from the input file into an array
};
TEST_ADD::TEST_ADD (void)
{
n=0;
}
void TEST_ADD::INPUTREAD (char * in_name) //will record the users input file (written in main.cpp)
//and store it as in_name
{
int i;
std::ifstream inputfile(in_name, std::ios::in);
std::cout << "Number of n before input file read : "<< n << std::endl;
inputfile >> n;
/*while(!inputfile.eof())
{
inputfile >> n;
//std::cout << std::setw(10) << n;
}*/
std::cout << "Number of n after input file read : " << n << std::endl;
std::cout << "There are ("<< n << ") numbers in the input file" << std::endl; //check
for(i=0;i<n;i++)
{
inputfile >> A[i];
std::cout << "A[" << i << "] = " << A[i]<< std::endl;
}
outputfile << "There are ("<< n << ") numbers in the input file" << std::endl;
}
Main File
#include <iostream>
#include <fstream>
#include <string.h>
#include <stdlib.h>
#include "Project2.h"
int main()
{
TEST_ADD b;
b.INPUTREAD("in_2.txt");
return 0;
}
Input File
1
2
5
9
The issue I think is the line
inputfile >> n;
This was the solution given to others, and this is what I used to use in class, but for some reason the text file isn't being read correctly so I must be doing something wrong.
When I use the following, I set up a cout statement to test my code and this is what I got
jason#jason-Satellite-S55-B:~/C++/Second_program$ g++ main2.cpp -o project2
main2.cpp: In function ‘int main()’:
main2.cpp:10:24: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
b.INPUTREAD("in_2.txt");
^
jason#jason-Satellite-S55-B:~/C++/Second_program$ ./project2
Number of n before input file read : 0
Number of n after input file read : 1
There are (1) numbers in the input file
A[0] = 2
As you can see it is only counting 1 entry and then when I check to see what number it stored in the array, it stores 2 which is the second number in the text file. It just skipped the first entry completely.
In case you were wondering, the actual out_2.txt file has
There are (1) numbers in the input file
I also tried the line
while(!inputfile.eof())
{
inputfile >> n;
//std::cout << std::setw(10) << n;
}
But that just brought up other problems where it counted 9 entries total, and the numbers stored in the array were large integers which aren't correct.
Any help is appreciated. Thanks
The INPUTREAD function takes a char * parameter. You are passing "in_2.txt", a literal string. Literal string are const char *, which is what the compiler's warning is telling you.
As you can see it is only counting 1 entry
The first number in the file is 1, so
inputfile >> n;
Read "1" into n.
and then when I check to see what number it stored in the array, it
stores 2 which is the second number in the text file.
Correct, that's the next number in the file. After the above statement read the "1", the code expects to see one number in the file, and starts reading. The next, and the only number the code reads is "2", which is what you see.
It just skipped the first entry completely.
No, it didn't. It was read by
inputfile >> n;
You need to add
4
to the beginning of the file, indicating that four numbers follow. The code reads the count of how many numbers are in the file, then proceeds to read those numbers. That's what you coded your program to do, and that's exactly what it's doing, here.

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.

(c++) Reading numeric data in a column from a txt file and determining highest value

So I'm trying to make a program that will read a txt file where time, voltage and ampere are stored, the text file looks like this http://pastebin.com/a0ZvYGmj, only ten times bigger (it's obnoxiously huge, so large that it didn't fit into a single pastebin).
So what I have to do is write a program that will read through the entire voltage column and detect the highest value (second column), then display it and the time it occurs (first column). I can also do it with the ampere, but that's optional.
Problem is I literally have no idea what to do, this is what I have managed to do so far
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
FILE * pFile;
char mystring [100];
pFile = fopen ("voltage.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
if ( fgets (mystring , 100 , pFile) != NULL )
puts (mystring);
fclose (pFile);
}
system ("PAUSE");
return 0;
}
But all that does is read the first entry of each of the 3 columns ("Time Volt Ampere"), so I probably have to start over.
Can anyone send me in the right direction? How do I read an entire column, them make the program detect the biggest number in said column?
I'm completely lost so any help would be appreciated.
If you have the option of using the file as an input, then you could use simple cin in order to get your values for Time,Volt and Amp. ( the only thing you need to keep in mind is to ignore first row because they are just names)
If you know that all three values in each row will be present, then you can create while loop that runs until EOF. Then you read 3 values (Time, Volt, Amp) and compare with the previous Volt.
If previous volt is larger - ignore this row and move on.
Else - keep current Time, Volt and Amp.
On the next iteration, compare new 3 values to the max value of Volt so far.
Here is my "quick and dirty" solution:
#include <iostream>
#include <string>
using namespace std;
int main()
{
// cin>>temp goes through names and ignores it since we don't need it
string temp;
cin >> temp;
cin >> temp;
cin >> temp;
float timeval = 0;
float volt = 0;
float amp = 0;
float timevalTemp = 0;
float voltTemp = 0;
float ampTemp = 0;
while(cin >> timevalTemp >> voltTemp >> ampTemp)
{
if(voltTemp > volt)
{
timeval = timevalTemp;
volt = voltTemp;
amp = ampTemp;
}
}
cout << "Max Time: " << timeval << endl;
cout << "Max Volt: " << volt << endl;
cout << "Max Amp: "<< amp << endl;
return 0;
}
Let me know if something is not clear. I ran it on your text file and it produces:
Max Time: 0.00035
Max Volt: 9.78167
Max Amp: 0.1473
You can try using fscanf. Please have a look at this How to use fscanf to read a file
After you read you will have to compare voltage values of each row to get max voltage. I hope you know how to do this.
First, you must use a llop construction so you read the whole set of lines. So try putting your fgetsinside of a while.
Next, you need to split each line by spaces. Use strtokfor that.
Next I'll recommend you keep a max_voltage variable and as you travel through the file, you assign it the current max value. Also, you need to keep track of that max_voltage variable's timecompanion so use another variable for that one (Google for "find max value in an array" if you have doubts about how to do it).
After you try that, post your work if you have some question/need clarifications.
Bye.
fgets reads file untill it encounter newline character, or end of file.
If fgets encounters eof before any character it'll return null pointer. So it should be okay if you change file reading code to:
while ( fgets (mystring , 100 , pFile) != NULL )
puts (mystring);
I would define what a line looks like:
struct Line {
double time, volt, ampere;
int linenumber;
};
istream& operator>>(istream& in, Line& line) {
++linenumber;
return in >> line.time >> line.volt >> line.ampere;
}
ostream& operator<<(ostream& out, const Line& line) {
return out << "Line: " << line.linenumber
<< " Time: " << line.time
<< " Volt: " << line.volt
<< " Ampere: " << line.ampere;
}
and use it with std::cin.
int main()
{
string dummy;
std::istream& in = cin;
in >> dummy >> dummy >> dummy;
Line max;
Line line;
while(in.good()) {
in >> line;
if (line.volt > max.volt) max = line;
}
cout << "Max line: " << max;
return 0;
}
(or you can replace cin with a file input stream:
#include <ifstream>
...
std::ifstream in(argv[1]);
...
)
You can use sort for that, it's a highly specialized merge-sort implementation that surely included in your cygwin distro. You can tell it which columns to sort on (the -k switch), and it both works with stdandard input and filename.
Then just take e.g. the first 4 lines of output to account for 'special' lines. Use cat -n to prepend line numbers.
$ cat -n input.txt | sort -r -k 2 | head -n 10
1 Time Volt Ampere
4796 0.2398 9.76417 0.147683
4795 0.23975 9.75667 0.147833
4794 0.2397 9.77333 0.147867
4793 0.23965 9.7575 0.14765
4792 0.2396 9.75167 0.147533
4791 0.23955 9.75833 0.147542
4790 0.2395 9.75583 0.147542
4789 0.23945 9.77 0.1476
4788 0.2394 9.75583 0.147317

How do I output specific characters from a txt file to specific points?

First task of the tutorial and I'm already stumped,
Right, I'm supposed to write down 3 numbers into a text file, open that file up, output all 3 numbers and the average. Managed to get the first 2 parts done but I've hit a wall at the actual output part.
Here is the contents of the text file exactly as it appears within the file:
25
10
12
And here is the code I have so far:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create an ifstream input stream for reading of data from the file
ifstream inFile;
inFile.open("ProgrammingIsFun.txt");
// Create an ofstream output stream for writing data to a file
ofstream outFile;
outFile.open("Results.out");
cout << "The first integer is " << endl;
cout << "The second integer is " << endl;
cout << "The third integer is " << endl;
cout << "The average is " << endl;
// Close the files since we're done with them
outFile.close();
inFile.close();
system("Pause");
return 0;
}
From what I understand the contents of the txt file can only contain those 3 numbers and nothing else (I could be wrong though)
Any help would be much appreciated.
I'm guessing that the preferred C++ way of reading integers from files would be:
int first, second, third;
inFile >> first;
inFile >> second;
inFile >> third;
You can then analogously output using the << operator on outFile.

std::fstream File prints junk at end of reading

Im writing a program to practice with the language, but im getting some pretty weird output from code that seems right to me.
The code:
#include <iostream>
#include <fstream>
#include <list>
struct Car
{
std::string make;
std::string model;
int partNo;
double price;
int quantity;
std::string partname;
};
void AddItem();
void _Update(int PartNo, int quantity);
void UpdateList(std::list<Car>& _Car);
int main()
{
std::list<Car> _Car;
UpdateList(_Car);
for(std::list<Car>::iterator iter = _Car.begin(); iter != _Car.end(); iter++)
{
std::cout << iter->make << " " << iter->model << " " << iter->partNo << " " << iter->price << " " << iter->quantity << " " << iter->partname << std::endl;
}
}
void UpdateList(std::list<Car>& _Car)
{
std::ifstream File("CarParts.txt");
if(!File.is_open())
std::cerr << "Bad file input....... closing....";
while(!File.eof())
{
Car tempObj;
File >> tempObj.make >> tempObj.model >> tempObj.partNo >> tempObj.price >> tempObj.quantity;
getline(File,tempObj.partname);
_Car.push_back(tempObj);
}
File.close();
}
Outpost given:
Pajero NA1H25 1 3.65 11 BLADE W/S WIPER Honda_Sivic R34gFk 2 4.97 15
ENGINE CHANGE 2 4.97 15
Notepad file:
Pajero NA1H25 1 3.65 11 BLADE W/S WIPER
HondaSivic R34gFk 2 4.97 15 ENGINE CHANGE
what is with the three numbers under the two lines i actually wanted printed out? It's really confusing me... Thanks if you can help!
This is a common issue people run into while reading file data in C++. The issue is your usage of eof. That flag is only set after an attempt to read data has failed.
Because of that, after reading the first two lines, it still has not hit the end of the file. It has read right up to it, but eof has not been set. Then it will loop around a third time, attempt to read 2 lines, and then exit after that. The problem is that you never check for eof before pushing the results of that third loop into your car list.
In your case, you can either move your eof check to after the getline call, or make use of the getline return value.
For example:
while(true)
{
Car tempObj;
File >> tempObj.make >> tempObj.model >> tempObj.partNo
>> tempObj.price >> tempObj.quantity;
if (!getline(File,tempObj.partname)) break;
_Car.push_back(tempObj);
}
This will check whether the data was read successfully before pushing.
For starters, set the namespace of the program to std to avoid the nasty std::string etc syntax.
Near the top of your file, under your imports, insert:
using namespace std;
It looks like the objective is to populate a list from a file.
Looking at this part:
File >> tempObj.make >> tempObj.model >> tempObj.partNo >> tempObj.price >> tempObj.quantity;
getline(File,tempObj.partname);
I think a better solution would be to parse each line withgetLine, and then parse the data accordingly with a space delimeter or a comma. Whitespace delimiters can be finiky.