It is necessary that the string is displayed under number N, which is generated by random.
What function should be used for this? Preferably Blue Functions (CSTDIO)
Answer 1, Authority 100%
You need the function of opening a file, read and closing. Open the file, read the line and increase the counter. When the counter has reached the desired, we display the string.
Schematic code:
char * getline (char * filename, int nedded) {
Char Line [250];
File * F = Open (FileName, "R");
int c = 0;
While (C & LT; Needed & Amp; & amp; not eof (f)) {
FSCANF (F, "% S", Line);
C++;
}
Close (F);
If (C! = NEDDED) {
RETURN NULL;
}
RETURN STRDUP (LINE); // Do not forget then free the buffer
}
char * line = getline ("input.txt", n);
If (Line) {
PrintF ("% s \ n", line);
FREE (LINE);
}
Answer 2, Authority 20%
// Indexing rows from zero
INT N_ReadLine (Const Char * Fname, Int N, Char * BUF, INT LEN) {
Char C;
File * FP = Fopen (FNAME, "RT");
if (FP == NULL)
Return 0;
While (! FeOF (FP) & amp; & amp; (n & gt; 0)) {
FSCANF (FP, "% * [^ \ N \ r]% C", & amp; c);
--n;
}
If (! FeOF (FP))
FGETS (BUF, LEN-1, FP);
ELSE.
* buf = '\ 0';
FClose (FP);
Return (int) (* buf! = '\ 0');
}
INT MAIN (Void) {
Char BUF [255];
// count a 2-line
if (n_readline ("levels.txt", 1, buf, sizeof (buf)))
Puts (BUF);
// count the 3rd line
if (N_ReadLine ("Levels.txt", 2, Buf, Sizeof (BUF)))
Puts (BUF);
Return 0;
}
Answer 3
In other answers, options are at clean C, and here you are on C++:
# include & lt; fstream & gt;
STD :: String Get_Line_N (Const Std :: String & Amp; FileName, Size_T n)
{
STD :: IFStream F (FileName);
// here would not prevent the verification that everything is in order with the file
STD :: String Line;
BOOL NOTRACHED = TRUE;
While (std :: getline (F, Line) & amp; & amp; notreached = (n-- & gt; 0))
;
if (! notreached)
Return Line;
ELSE.
// there is no such line, report error
// For example, throw a suitable exception.
Throw Std :: Range_ERROR ();
}
For comparison, here on C #:
string getlinbynumber (String Filename, Int N)
{
var line = file.Readlines (FileName) .Skip (n) .firstordefault ();
if (Line! = NULL)
Return Line;
ELSE.
Throw New IndexOUTOFRANGEEXCEPTION ();
}
Exercise: Why do you need a variable NotReached
? Why not check the value n
?