How to Read Multiple Values From Console in C#

  1. #1

    GenghisAhn is offline

    Registered User


    How to browse in multiple values from a text file

    I am working on a project for my programming class, only I am having problems with getting values from a text file and assigning them to variables in my code. I have multiple lines of numbers in my text file, and each line tends to vary in the amount of floats and integers.

    Specifically:
    15 twenty fifty 1.0 0.0
    5 4 v.0
    vi four 5.0
    seven 4 5.0
    eight 4 v.0
    -1

    There are several data sets every bit the one above.
    The showtime line consists of matrix and parameters for processing the values within the matrix, in that location are 5 values for the start of each data gear up. Afterwards at that place are several lines of iii values. Those are values that volition exist put into the matrix (m,n,value). And then the second line for example: assortment[5][4]=5.0.
    The final line of each information is ever a -1. This flags the end of the data set up.

    I have to create matrices multiple times, and I just need help scanning in the numbers.
    Hither'south what I have so far, merely It'due south not working:

    Code:

                            while(fscanf(fin,"%d %d %d %lf %lf",&thou,&n,&itmax,&eps,&evalue) == 5)                        {                                                  /*some printing commands*/                                                                          while(fscanf(fin,"%d",&i)==ane)                                                  {                                                  if(i != -1)                                                  {                                                  fscanf(fin,"%d %lf",%j,%value);                                                  }                                                  else{break;}                                                  }                        }                                              


  2. #2

    qny is offline

    Registered User


    Read from the file with fgets() ... to a string.
    Read from the string with sscanf()...

    Code:

    while (fgets(buffer, sizeof buffer, fin)) {     chk = sscanf(buffer, "%d %d %d %lf %lf", &thousand,&n,&itmax,&eps,&evalue);     if (chk == 1) {         if (thou == -1) {             /* input terminated */         } else {             /* unexpected value */         }     } else {         if (chk == 3) {             /* rescan with a pointer exercise double in the 3rd position */             chk2 = sscanf(buffer, "%d %d %lf", &i, &j, &value);             if (chk2 == three) {                 /* utilize i, j, and value */             } else {                 /* this didn't happen */             }         } else {             if (chk == 5) {                 /* employ m, n, itmax, eps, and evalue */             } else {                 /* invalid line */             }         }     } }


  3. #3

    GenghisAhn is offline

    Registered User


    Question would I offset off with:
    [code]
    while(fgets(buffer, sizeofbuffer, fin)!=Zip)
    [code/]

    if I wanted to keep this up till the end of the text file?


  4. #4

    Click_here is offline

    TEIAM - trouble solved


    Why use fgets then sscanf instead of fscanf?

    Fact - Beethoven wrote his kickoff symphony in C


  5. #v

    qny is offline

    Registered User


    Quote Originally Posted by GenghisAhn View Post

    Question would I beginning off with:
    [code]
    while(fgets(buffer, sizeofbuffer, fin)!=NULL)
    [code/]

    if I wanted to keep this upwards till the terminate of the text file?

    Yes, that's the idea.


  6. #half-dozen

    qny is offline

    Registered User


    Quote Originally Posted by Click_here View Post

    Why use fgets and then sscanf instead of fscanf?

    fgets() retrieves and removes information from the stream (in groups of lines). That data is saved in a string and yous can use it you like, for case, with sscanf()
    fscanf() retrieves and removes data from the stream (in heteregeneous groups depending on the format string). That information is put into variables and is not reusable.

    Recovering from errors in fgets() is piece of cake.
    Recovering from errors in fscanf() in impossible.


  7. #7

    Click_here is offline

    TEIAM - problem solved


    I don't know if I concur with that... Especially considering the OP is dealing with a file, not a stream.

    Fact - Beethoven wrote his first symphony in C


  8. #8

    Nominal Animal is offline

    Ticked and off


    I hold with qny's arroyo, except that I'd utilize a nested loop like this:

    Code:

                          char    linebuf[200]; /* Length of longest possible input line + 1 */     char   *line;      int     rows, cols, iterations;     double  eps, err;      int     row, col;     double  value;       /* Loop over matrices: */     while (1) {          /* Read new line from standard input. */         line = fgets(linebuf, sizeof linebuf, stdin);         if (!line) {             /* No more input, no more matrices. */             break;         }          /* Parse matrix declaration. */         if (sscanf(line, "%d %d %d %lf %lf", &rows, &cols, &iterations, &eps, &err) < 5) {              /* Bad line. Remove newline at stop of line. */             line[strcspn(line, "\r\n")] = '\0';              fprintf(stderr, "%southward: Invalid matrix declaration.\n", line);              /* Break out of loop, only as if input had concluded. */             interruption;         }          /*          * TODO: initialize a suitable matrix structure.         */          /* Sparse matrix chemical element loop. */         while (ane) {              /* Read new line from standard input. */             line = fgets(linebuf, sizeof linebuf, stdin);             if (!line) {                 fprintf(stderr, "Alert: Premature end of input while reading matrix elements.\n");                 break;             }              /* Matrix chemical element? */             if (sscanf(line, " %d %d %lf", &row, &col, &value) >= 3) {                  /*                  * TODO: Prepare matrix element at row 'row', column 'col' to 'value'                 */              } else             if (sscanf(line, " %d", &row) >= 1 && row == -1) {                 /* Cease of matrix elements */                 break;              } else {                 /* Remove newline from the finish of line. */                 line[strcspn(line, "\r\n")] = '\0';                 fprintf(stderr, "%southward: Not a matrix element.\northward", line);                  /* Break out; care for the mistake as if it was a -ane. */                 break;              }         }     }
    You could also add a flag you set up before each break in the inner loop, and check it at the stop of the outer loop, to differentiate betwixt input format errors and normal operation.

    If you wanted to add together support for skipping empty lines (containing at most only white-infinite characters) and comment lines (lines showtime with a # or a ; ) all you lot demand would be to add

    Code:

                          /* Skip leading whitespace in the line. */         line += strspn(line, "\t\n\5\f\r ");          /* Skip comment lines and empty lines. */         if (*line == '#' || *line == ';' || *line == '\0')             continue;
    after each if (!line) statement.


  9. #9

    christop is offline

    Registered User


    Quote Originally Posted by Click_here View Post

    I don't know if I agree with that... Especially considering the OP is dealing with a file, not a stream.

    In C, a file is a stream of bytes.


  10. #x

    Click_here is offline

    TEIAM - problem solved


    In C, a file is a stream of bytes.

    Off-white enough - I would recall that there is a difference betwixt, say, stdin/stdout/stderr (which I would call a stream), to a text/binary file (which I would call a file). However, in that location it is in section 7.xix.three File of the C99 Typhoon - You are definitely right in saying that a file is a stream.

    Recovering from errors in fgets() is like shooting fish in a barrel.
    Recovering from errors in fscanf() in impossible.

    What I was trying to question was the above statement. How is using fscanf "impossible" to recover from when reading from a decadent text file, but using fgets/sscanf is with regard to a text file? All fgets does is put the line in a buffer showtime - And then you are using sscanf which has the same problems equally fscanf.

    The data won't be lost, it'due south a text file - Have you considered fseek?

    If there is a corrupt file, do yous want to keep reading it? For the OP'south code, I'd say no. If annihilation is unexpected, fputs a message on stderr and shut the program.

    Notwithstanding, I am getting off rail here disagreeing with the statement above saying "impossible" - For the record: I don't take a problem with the fgets solution, I have a problem with the word "impossible".

    Fact - Beethoven wrote his showtime symphony in C


  11. #11

    Nominal Animal is offline

    Ticked and off


    Quote Originally Posted by Click_here View Post

    All fgets does is put the line in a buffer starting time - And and so you lot are using sscanf which has the same problems equally fscanf.

    You can employ multiple sscanf() calls on the same buffered line, to see which one works. If a pattern works partially, then fscanf() consumes the initial role; there is no way to get information technology dorsum.

    Note that in POSIX systems, fseek() and ftell() do not work for pipes, sockets, or FIFOs. Some implementations might allow it in some cases, only the standard says information technology does non need to piece of work for pipes, sockets, or FIFOs. In that location really is no way to go back the stuff fscanf() consumed. That'southward where the impossible comes from.

    For a practical example, assume you lot have an input line consisting of some number of records that start with a single-word proper name, followed past two numbers. A bug elsewhere causes a number to be misoutput -- this exact instance is from Fortran code that specified a too-narrow output field. So, instead of having

    Code:

    automobiles 153398.23 142 123foobar 0.0 0
    yous have

    Lawmaking:

    automobiles *****.** 142 123foobar 0.0 0
    If you utilise fscanf(..., " %63s %lf %d",...), it volition neglect at the asterisks, but volition have consumed the "automobiles" part. How practise you recover? How practice you skip the asterisks? You lot don't, at that place is no simple, reliable way. The all-time you can do is fscanf(..., "%*[^\n]"); in an endeavour to discard the rest of the line.

    If y'all redo the fscanf(), you'll become the "*****.**" as the name string, 142 every bit the floating-point number, and 123 as the integer. The next fscanf() will read the proper noun foobar, 0.0 as the floating-betoken number, and 123 every bit the integer.

    If you read the input line past line, y'all'll notice that the sscanf() could not catechumen all three values, so you output an error or a warning. Remove the trailing newline from the line, and tell the user that the line has bad format. If you saved the sscanf() return value (the number of conversions it did), you tin fifty-fifty tell the user which field was in fault. And then yous discard the line, and go on to the adjacent line.

    I likewise prefer to let my input lines contain comment lines starting with a # or a ; . With fscanf() that is very difficult, but reading line-by-line, it is trivial.

    Last edited by Nominal Beast; x-29-2012 at 07:10 PM.


  12. #12

    Click_here is offline

    TEIAM - problem solved


    I appreciate that there are cases that fseek will not work. Nevertheless, I was explicitly talking about text files.

    ... from a corrupt text file
    ... with regard to a text file
    ...
    it's a text file

    Changing the input to have "**" does not fit the OP's specs. If the text file does non fit the specs, the programme should terminate with an error - Just similar your code did.

    And in one case once again

    For the tape: I don't have a problem with the fgets solution, I have a problem with the give-and-take "incommunicable".

    Fact - Beethoven wrote his offset symphony in C


  13. #13

    qny is offline

    Registered User


    Quote Originally Posted past Nominal Beast View Post

    That'due south where the incommunicable comes from.

    Thank you Nominal Animal

    Quote Originally Posted by Click_here View Post

    I don't know if I agree with that... Especially because the OP is dealing with a file, not a stream.

    Ok ... I hold the "incommunicable" is a teeny tiny little too strong.
    I better my argument to

    Recovering from data errors in fgets() is like shooting fish in a barrel.
    Recovering from
    data errors in fscanf() is impossible in many situations.


harrisprityruccon.blogspot.com

Source: https://cboard.cprogramming.com/c-programming/151773-how-scan-multiple-values-text-file.html

0 Response to "How to Read Multiple Values From Console in C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel