Advertisement

fscanf with strings

Started by May 15, 2001 05:03 PM
4 comments, last by Zoe 23 years, 9 months ago
Hi, I''m using the following code to populate my array with ints. #include int list[5]; FILE *fp = fopen("myfile.txt","rt")if(fp!=NULL) { for(int a=0; a<5; a++) { fscanf(fp,"%i",&list Thanks in advance! ' Target=_Blank>Link
what exactly is your question ??

{ Stating the obvious never helped any situation !! }
Advertisement
Hmmm... that was bizarre... the last part of the post got chopped off...

Well anyway, here it is again...

#include
int list[ 5 ];
FILE *fp = fopen("myfile.txt","rt")
if(fp!=NULL) {
for(int i=0; i<5; i++)
{
fscanf(fp,"%i",&list ); <br>} <br>fclose(fp);<br>}<br><br>I wanted to know how I would get doubles and strings to work with the above code… Every time I've tried I get errors.<br><br>Any assistance would be helpful. <br><br>Edited by - Zoe on May 15, 2001 10:16:43 PM <br><br>Edited by - Zoe on May 15, 2001 10:17:41 PM
  #include <stdio.h>// INTEGERSint list[5];FILE *fp = fopen("myfile.txt","rt")if(fp!=NULL) {  for(int i=0; i<5; i++) {    fscanf(fp,"%i",&list[i]);   }   fclose(fp);}// STRINGSchar list[5][100];FILE *fp = fopen("myfile.txt","rt")if(fp!=NULL) {  for(int i=0; i<5; i++) {    fscanf(fp,"%s",list[i]);   }   fclose(fp);}// DOUBLESdouble list[5];FILE *fp = fopen("myfile.txt","rt")if(fp!=NULL) {  for(int i=0; i<5; i++) {    fscanf(fp,"%lf",&list[i]);  }   fclose(fp);}  


Resist Windows XP''s Invasive Production Activation Technology!
http://druidgames.cjb.net/
Thanks Null and Void....

One question though...

Why the [ 100 ] after the list [ 5 ] ?

What does that do?
char list[5];

That''s a character array of 5 elements. Not enough to hold my name.

char list[100];

That''s a character array of 100 elements (a single string). If you want an array of strings, you need to do

char list[5][100];

Then you have an array of strings. So if I had five strings
"I"
"Am"
"Not"
"A"
"Lawyer"
and read them into the arrays,

printf( "%s", list[2][2]); // bad C; been coding C++ too long

would print the letter "t" to the screen.

---
Those who can do nothing criticize; those who can, critique.

This topic is closed to new replies.

Advertisement