After much searching I cannot find a particular way to get a datafile into my structure. I understand how to create and manipulate the structure. C does not play nicely with strings is another thing I have noticed. I have tried many examples of how to do this but none of them work.

#include <stdio.h>
#include <string.h>
int main()
{
	struct citydata
	{
		char city[20];
		int temp;
	};
	
	struct citydata values[15];
//These will be used later
	struct citydata Avg;
	struct citydata high;
	struct citydata low;
	
	FILE * inp;
	int reccount = 0;
	int x = 0;
	char s;
	int n;
	
	inp = fopen("input.txt", "r");
	if(!inp)
	{
		printf("Unable ot open file\n");
	}
	
	while (fscanf(inp,"%s %d",&s, &n) != EOF) 
	{
		values[x].city = s;
		values[x].temp = n;
		x++;
	}
	
	fclose(inp);
}

/*input.txt contains this
 Grand_Forks 34
 Devils_lake 36
 Fargo 35
 Whapeton 34
 Jamestown 36
 Langdon 27
 Bismarck 35
 Minot 39
 Garrison 38
 Williston 32
 Dickenson 38
 Hettinger 36

 */

you can't say values[x].city = s ... you must do something like strcpy(values[x].city, s) ... also dont put the "&s" when getting a string. just put "s"

while (fscanf(inp,"%s %d",s, &n) != EOF) 
	{
		strcpy(values[x].city, s);
		values[x].temp = n;
		x++;
	}

the reason is that "s" and "values[x].city" are actually pointers to a character array, and you can't simply make an assignment to copy the array.

you can't say values[x].city = s ... you must do something like strcpy(values[x].city, s) ... also dont put the "&s" when getting a string. just put "s"

while (fscanf(inp,"%s %d",s, &n) != EOF) 
	{
		strcpy(values[x].city, s);
		values[x].temp = n;
		x++;
	}

the reason is that "s" and "values[x].city" are actually pointers to a character array, and you can't simply make an assignment to copy the array.

I found this solution

while (fscanf(inp,"%s %d",strcpy(values[x].city, %values[x].temp) != EOF) 
	{
		x++;
	}

Nice. Try it with the city Des Moines or Los Angeles and let us know how it works.

following his posted .TXT file example, i can see that Des_Moines and Los_Angeles will work just fine.

:P

That'll teach me to look first...

s should be declared as char array of size 20

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.