Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is some code that will do what you are asking. I think it will help you understand how string functions work a little better. Note - I did not make many assumptions about how well conditioned the input and text file are, so there is a fair bit of code for removing whitespace from the input, and for checking that the match is truly "the first word", and not "the first part of the first word". So this code will not match the input "hello" to the line "helloworld 123 234" but it will match to "hello world 123 234". Note also that it is currently case sensitive.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(void) { char buf[100]; // declare space for the input string FILE *fp; // pointer to the text file char fileBuf[256]; // space to keep a line from the file int ii, ll; printf("give a word to check:\n"); fgets(buf, 100, stdin); // fgets prevents you reading in a string longer than buffer printf("you entered: %s\n", buf); // check we read correctly // see (for debug) if there are any odd characters: printf("In hex, that is "); ll = strlen(buf); for(ii = 0; ii &lt; ll; ii++) printf("%2X ", buf[ii]); printf("\n"); // probably see a carriage return - depends on OS. Get rid of it! // note I could have used the result that ii is strlen(but) but // that makes the code harder to understand for(ii = strlen(buf) - 1; ii &gt;=0; ii--) { if (isspace(buf[ii])) buf[ii]='\0'; } // open the file: if((fp=fopen("myFile.txt", "r"))==NULL) { printf("cannot open file!\n"); return 0; } while( fgets(fileBuf, 256, fp) ) { // read in one line at a time until eof printf("line read: %s", fileBuf); // show we read it correctly // find whitespace: we need to keep only the first word. ii = 0; while(!isspace(fileBuf[ii]) &amp;&amp; ii &lt; 255) ii++; // now compare input string with first word from input file: if (strlen(buf)==ii &amp;&amp; strstr(fileBuf, buf) == fileBuf) { printf("found a matching line: %s\n", fileBuf); break; } } // when you get here, fileBuf will contain the line you are interested in // the second and third word of the line are what you are really after. } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload