My code is supposed to do this:
Read the name of the file and try to open it, providing an error message if no file with the given name exists, as in a).
Read the first line of the file to determine the value of N.
Generate randomly an integer K in the range [1 .. N].
Read the contents of the file until it reaches the K-th row (not counting the first row).
Display the contents of that line on the screen.
For example:
Contents of a text file (ex: beatles.txt):
17
In the town where I was born
Lived a man who sailed to sea
And he told us of his life
In the land of submarines
So we sailed up to the sun
Till we found the sea of green
And we lived beneath the waves
In our yellow submarine
We all live in a yellow submarine
Yellow submarine, yellow submarine
And our friends are all on board
Many more of them live next door
And the band begins to play
As we live a life of ease
Everyone of us has all we need
Sky of blue and sea of green
In our yellow submarine
Execution result:
FILENAME? beatles.txt
SENTENCE: We all live in a yellow submarine // when K, randomly generated, was equal to 9
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<cctype>
#include<vector>
#include <cmath>
#include <math.h>
using namespace std;
int main () {
srand ((unsigned int) time(0));
string filename;
cout << "FILENAME? ";
cin >> filename;
ifstream fin(filename.c_str());
if (fin.is_open())
{cout << "SENTENCE: ";
string line;
char sline[256];
std::string newline;
vector<string> list;
while(getline(fin, line))
{
strcpy(sline, line.c_str());
int N;
N = atoi(sline);
int k;
k = rand() % N + 1;
for (int i=0; i<(k+1);i++)
{
getline(fin,newline);
}}
cout << newline;
fin.close();}
else cout << "ERROR: File not found!";
return 0;
}
Everytime I run the program it is returning:
FILENAME? beatles.txt
SENTENCE: Many more of them live next door
And the band begins to play
As we live a life of ease
Everyone of us has all we need
Sky of blue and sea of green
In our yellow submarine
I think it is a problem with the second getline but i don't know how to solve it.
Can you help?