...

View Full Version : Problem with C Strings



sylverfyst
10-26-2009, 01:56 AM
I have a problem that I have to finish and I was wondering if I could get some help. What I have to do is read in a file from the command prompt and have it print out strings one per line. The strings have to be over 4 characters long and cannot contain non printable characters. I wrote my code and went over it with the gcc compiler only to get the warning

"myStrings.c: In function `get_strings':
myStrings.c:17: warning: passing arg 2 of `strcpy' makes pointer from integer without a cast"

why doesn't it compile? or is there some integral flaw with my code? I'm very grateful for any help.



#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
char fname[100];
char *p;
FILE *in_file;

void get_strings(FILE *fp){
char str[100];
char ch;
char ch2;

ch = fgetc(fp);
while(ch != EOF){
while(isprint(ch) != 0){
strcpy(str,ch);
ch2 = fgetc(fp);
if(strlen(str) > 4 && isprint(ch2) == 0) {
printf("%s \n",str);
break;
}
else
ch = ch2;
}
ch = fgetc(fp);
}
}
int main(int argc, char *argv[])
{
printf("Enter a filename: ");

if(fgets(fname,sizeof(fname),stdin) != NULL){
if((p = strchr(fname, '\n')) != NULL)
*p = '\0';
}

in_file = fopen(fname, "r");

if(in_file == NULL){
printf("Cannot open %s \n", fname);
exit(8);
}
get_strings(in_file);
}

oesxyl
10-26-2009, 02:15 AM
ch is char not a pointer, char *.



int contor = 0;
while((ch = fgetc(fp)) != EOF){
if(isprint(ch)){
printf("%c",ch);
contor++;
}
if(contor >= 4){
printf("\n");
contor = 0;
}
}


your first while looks like a do-while with first fget inside. Also is a bad idea to use a loop inside another loop if you don't need it.

best regards

sylverfyst
10-26-2009, 02:18 AM
*facepalm* thank you I clearly need to sleep or something, I should've caught that. Nonetheless, thank you

oesxyl
10-26-2009, 02:22 AM
*facepalm* thank you I clearly need to sleep or something, I should've caught that. Nonetheless, thank you
you are welcome, :)
I know it's a homework, :) anyway you was very close to what you need and that error was not so hard to detect for you after you forget the code and read again after a break, :)

best regards



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum