Note that there are some explanatory texts on larger screens.

plurals
  1. POC strings from text file
    text
    copied!<p>I am new to C programming language. How do you search a particular string from a text file and make them into array, then produce a single string from those array?</p> <p>text file:</p> <pre><code>name1,name2,name3,type1,g1,g2,g3 name1,last1,last2,type2,g4,g6,g7 foo1,foo2,foo3,type3,gx,g3,g5 foo1,doo1,doo2,type4,g1,gt,gl </code></pre> <p>The output should be in 1 string, not separated so if let's say it is </p> <pre><code>printf("%s", strings); </code></pre> <p>It gives output like:</p> <pre><code>2 records found Name: name1,name2,name3 type: type1 g1 type: g1 g2 type: g2 g3 type: g3 Name: name1,last1,last2 type: type2 g1 type: g4 g2 type: g6 g3 type: g7 </code></pre> <p>My attempt so far is getting the text file and search the string:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(){ char tmp[1000]; int count=0; FILE *fp=fopen("test.csv","r"); while(fgets(tmp, sizeof(tmp),fp) != NULL){ if (strstr(tmp, "name1")){ count = count + 1; printf("%s", tmp); } } } </code></pre> <p>which only give output:</p> <pre><code>name1,name2,name3,type1,g1,g2,g3 name1,last1,last2,type2,g4,g6,g7 </code></pre> <p>Attempt in progress:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main(){ char tmp[1000]; int count=0; char *string; char *name1, *name2, *name3, *type,*g1,*g2,*g3; FILE *fp=fopen("test.csv","r"); while(fgets(tmp, sizeof(tmp),fp) != NULL){ name1 = strtok(tmp,","); name2 = strtok(NULL,","); name3 = strtok(NULL,","); type= strtok(NULL,","); g1= strtok(NULL,","); g2= strtok(NULL,","); g3= strtok(NULL,","); if (strstr(tmp, "name1")){ count = count + 1; string = malloc(sizeof(*string)); sprintf(string, "\n%d record(s) found.\n\nName: %s, %s, %s \nType: %s\ng1 type: %s\ng2 type: %s\ng3 type: %s", count, name1, name2,name3,type,g1,g2,g3); } } printf("%s", string); } </code></pre> <p>with output:</p> <pre><code>2 record(s) found. Name: name1, last1, last2 Type: type2 g1 type: g4 g2 type: g6 g3 type: g7 </code></pre>
 

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