while loop used to read a .dat file c++ [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 13 days ago.
Improve this question
I am trying to read a .dat file of 11 numbers, the code detects the time incrementation between them(this is an arbitrary value set in the .dat file). I am using while loop to process the other numbers in the fil, but when I use it, only the first value of the file appears on the graphics screen followed by zeros.
my code is as follows:
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
//int k;
double npts;
double time_inc;
//double sensor;
double seismicData;
//double new_double;
ifstream myFile;
ifstream fin;
//ifstream dataOutput;`
int main()
{
//this takes the data and analyses the number of points as well as the time incr.
ifstream fin("SEISMIC.dat", ios::in);
myFile.open("SEISMIC.dat");
fin >> npts;
cout << "Number of data points: " << npts;
fin >> time_inc;
cout << " Time incrementation:" << time_inc;
int num;
//myFile.open("SEISMIC.dat");
if (!myFile) {
cout << "Error: file could not be opened" << endl;
exit(1);
}
myFile >> num;
fin >> num;
//myFile >> seismicData;
while (!myFile.eof()) {
cout << "Next number is:" << num <<endl;
myFile >> num;
//cout << "Next number is:" << fin << endl;
//cout << seismicData << endl;
//myFile >> seismicData;
}
myFile.close();
}
I'm wondering if anyone could help me out. Attached is a screenshot of the .dat file

Here's some code to read all the numbers from a text file and echo them to the standard output.
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("SEISMIC.dat");
if (!file.is_open())
std::cerr << "cannot open file\n";
int num;
while (file >> num)
std::cout << num << '\n';
}
As you can see, not much code is needed. However this code will not work if the file is not in the format you described.

Related

String doesn't want to store a 2700 character word

I'm trying to make a program that prints all the numbers from 100-999. After that you get to choose how many numbers you want to find. Then you type the number's position and it will be outputed.
There is one problem. The string, named str, stops storing at the number 954.
Here's the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
//Prints to myFile the numbers from 100 to 999 without a space in between. Like this: 100101102...999
ofstream myFile("numere.txt");
for(int i = 100; i <= 999; i++)
myFile << i;
//Makes the string str to store the line: 100101102103...999. But only stores until 954 (100101102..954)
ifstream myFileRead("numere.txt");
string str;
while(getline(myFileRead, str))
cout << str << endl;
//Ouputs the lenght that should be 2700 but is instead 2565
cout << endl;
cout << "String legth: " << str.size() << endl;
cout << endl;
int n, k;
cout << "Enter how many numbers do you want to find: ";
cin >> n;
for(int i = 1; i <= n; i++){
cout << "Enter number position(it starts from 0) : ";
cin >> k;
cout << "Here's the number on position " << k << ": " << str.at(k);
cout << endl;
}
system("pause>0");
}
Thanks for your attention. I’m looking forward to your reply.
C++ streams are buffered. When you use << to write to a file it is not immediately written to the file.
Try to close or flush the ofstream before you read from it:
myFile.close(); // or...
myFile.flush();
For more details I refer you to flush() and close().
PS: Actually it is rather rare that you need to close a fstream explicitly. You wouldn't need to do it when you used seperate functions for writing and reading:
void write_to_file() {
std::ofstream myFile("numere.txt");
//...
}
void read_from_file() {
std::istream myFile("numere.txt");
//...
}
Because the destructor of ofstream already closes the file.

.EOF Causing Seg Fault when reading file :FIXXED [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
When I run my program it works the first time, the correct input is read and output is written to my output file but once I run it a second time it doesn't write anything the file is just blank even though it reads everything correctly. I can't seem to understand where its messing up or how and I really want to know. The two images are my first and second runs just that after the second run my output file is blank.
first run
second run
#include<iostream>
#include<iostream>
#include<cstdlib>
#include<time.h>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int i=0;
int number; // The correct number
int guess=0; // The user's guess
int numGuesses=0; // The number of times the user has guessed
string lines;
string player;
ifstream ifile;
ofstream ofile;
//ofstream myfile;
//
string names[10];
int scores[10];
ifile.open("high_score.txt");
string first_last_name;
string temp;
int score;
int index=0;
string title;
bool topten=false;
cout <<"Welcome to the number guessing game. The top 10 best scores so far are: "<<endl;
while(!ifile.eof())
{
//getline(ifile,lines);
ifile >>first_last_name;
//cout << first_last_name;
ifile >> temp;
first_last_name.append(" ");
first_last_name.append(temp);
ifile >> score;
names[index]=first_last_name;
scores[index++]=score;
}
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
for (int i=0; i < 10; i++)
{
cout << names[i] << " " << scores[i] <<endl;
}
// Seed the random generator.
srand(static_cast<int> (time(NULL)));
// Generate a random number between 1 and 100.
number = (rand() % 100) + 1;
cout << "Let's play the number guessing game! What is your name? " <<endl;
getline(cin,player);
cout << endl;
while(guess!=number)
{
cout << "guess the number the computer randomly picked between 1 - 100: ";
cin >> guess;
numGuesses++;
// Check if the user has guessed the correct number.
// If not, tell him if his guess is too low or too high
if(number > guess)
{
cout << "sorry, your guess is too low" << endl;
}
else if(number < guess)
{
cout << "sorry, your guess is too high" << endl;
}
else
{
cout << "You guessed right!!!!"<<endl;
cout << "You win!!!" << endl;
break;
}
}
cout << "It took you "<< numGuesses << " guesses "<< player<< endl;
////////////////////////////////////////////////////////////////////////
if (numGuesses<4)
{
cout << "Amazing! Or was it luck" << endl;
}
else if(numGuesses<6)
{
cout <<"That's a very good score..." <<endl;
}
else if (numGuesses<8)
{
cout << "That's pretty good but you can do better..." << endl;
}
else if ( numGuesses<10)
{
cout << "Not too shabby, but not too good either..."<< endl;
}
else
{
cout << "What a terrible score!..." << endl;
}
for(int i=0; i < 10; i++)
{
if(numGuesses <= scores[i])
{
for( int k=9;k>i;k--)
{
scores[k]=scores[k-1];
names[k]=names[k-1];
}
scores[i]=numGuesses;
names[i]=player;
topten=true;
break;
}
}
if(topten==true)
{
cout << "Hey, you made it to the top ten , Congratzzzzzzzz!!!!" <<endl;
}
ofile.open("high_score.txt");
for(int i=0;i<10;i++)
{
ofile <<"\t"<< names[i] << " " << scores[i] <<endl;
ofile << endl;
}
return 0;
}
You need to close the input file before you open the output file, since they are both referring to the same file.
The closing can be done explicitly by calling ifile.close() or implicitly by making ifile go out of scope before you open the output file.
The latter can be done like this:
{
ifstream ifile;
ifile.open("high_score.txt");
// do stuff with ifile
}
ofstream ofile;
ofile.open("high_score.txt");
// do stuff with ofile
Where is ifile.close() and ofile.close()
you should close else your stream will go into invalid state.

I'm trying to count the number of lines in my file but my counter prints out 0 every time

#include <iostream>
#include <fstream>
using namespace std;
void get_input (ifstream& ifile){
std::string filename;
cout << "Input filename:";
cin >> filename;
if (ifile.fail()){
cout << "File is not found"<< endl;
}
int ID, score, count = 0;
while (1){
ifile >> ID >> score;
if (ifile.eof()) break;
++count;
}
ifile.close();
cout << ID << endl;
cout << count << endl;
cout << score << endl;
}
main:
int main(int argc, const char * argv[]) {
ifstream file;
get_input (file);
return 0;
}
I changed it to std::string, but the counter still prints out 0. I am taking int data from a file that has 2 columns. I also need to count the number of lines in the file.
You have more than one problem.
As someone else mentioned, you're not actually opening any file.
if (ifile.fail()) <<this is failing & does not get entered
Instead try
if (!ifile.is_open())
And it will show that you're not opening anything.
Once you open the file like so;
ifile.open(filename);
Your code should work, however I can't see where you're checking for line returns. I'll leave that as an exercise for you to follow up. Try searching for std::getline.

user input and reading file contents

For full disclosure this is an assignment for my programming class and I just want tips or advice on some of the code.
Assignment details just for background information purposes.
Write a program that will read a number 1-100 from the user, and the name of a data file, and will tell the user what word is in the file and how many times the numbers shows up in the data file. Validate input number (keep asking until valid) and validate the file was successfully open.
text file contents: Darling 10 20 21 19 20
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // Needed for exit()
using namespace std;
int main()
{
ifstream inputFile;
string fileName;
int value;
cout << "Enter the file name: ";
getline(cin, fileName);
// Open the file
inputFile.open(fileName.c_str());
// Check for successful opening
if(inputFile.fail())
{
cerr << "Error Opening File" << endl;
exit(1);
}
cout << "\nThe file has been successfully opened for reading.\n";
cout << "Pick a number between 1 through 100. ";
cin >> value;
if (value >= 1 && value <= 100)
{
cout << value << " is in the acceptable range.\n";
}
else
{
cout << "Please enter a number from 1 to 100. ";
cin >> value;
}
string word;
int number;
int count = 0;
infile >> number;
// Read a file until you've reached the end
while (!inputFile.eof())
{
if (number == x)
{
sum1++
}
infile >> number;
}
cout << sum1;
while (!inputFile.eof())
{
inputFile >> word;
if (word == "input")
{
count++;
}
}
// Close the file
inputFile.close();
return 0;
}
Any tips or advice would be greatly appreciated since I'm lost when it comes to the fstream portion of this assignment right now.
Thanks in advance,
James

reading from a text file that contains numbers and characters

I recently learned how to read data from a text file, but I would like to continue expanding my knowledge on that matter. I would like to read files that contain numbers and characters. Can anyone give me some advice please?
The following is the code I wrote to read numbers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {
ifstream infile("input.txt", ios::in);
if (!infile) {
cout << "Inputxxxxx file could not be opened" << endl;
exit(1);
}
ofstream outfile ("outputt.txt", ios::out);
if (!outfile) {
cout << "inputssss file could not be opened " <<endl;
exit(1);
}
int number;
int answer[10];
for (int i = 0; i < 9 ; i++) {
infile >> number;
answer[i]=number;
cout << answer[i] << " ";
outfile <<answer[i]<< " ";
}
return 0;
}