How to read empty string in C -
i have problem reading empty string in c. want read string following -
- ass
- ball
- (empty)
- cat
but when use gets() not treat (empty) string[2]. reads 'cat' string[2]. how can solve problem?
char str1[15002][12]; char str2[15002][12]; char s[25]; map<string,int> map; int main() { int ncase, i, j, n1, n2, count, case; freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); scanf("%d",&ncase); case = 1; while(ncase > 0) { map.clear(); //this necessery part scanf("%d %d\n",&n1,&n2); count = 0; printf("n1=%d n2=%d\n",n1,n2); for(i = 0; < n1; i++) { gets(str1[i]); } for(i = 0; < n2; i++) { gets(str2[i]); } //end of reading input for(i = 0; < n1; i++) { for(j = 0; j < n2; j++) { strcpy(s,str1[i]); strcat(s,str2[j]); if(map[s] == 0){ count += 1; map[s] = 1; } } } printf("case %d: %d\n", case, count); case++; ncase--; } return 0; } and input can like
i have given code here. input may like
line1>1 line2>3 3 line3>(empty line) line4>a line5>b line6>c line7>(empty) line8>b and expect
str1[0]=(empty). str1[1]=a; str1[2]=b; and
str2[0]=c; str2[1]=(empty); str2[2]=b;
ok, @ last found problem. line
printf("n1=%d n2=%d\n",n1,n2); which creates problem in taking input gets(). instead of taking newline integer n1, n2, take newline ("%c",&ch) , okay.
thanks answered me.
chances are, string contains \r\n\0 (or \n\r\0 - never remember comes first). \r\n newline on windows , \0 terminating character of string.
in general, if first character of string \r or\n, read empty string. fwiw should work on platforms:
char* string; // initialize string , read if (strlen(string) == 0 || string[0] == `\r` || string[0] == `\n`) // string empty update: mention use gets, , read file. however, latter need fgets, there confusion here. note fgets includes trailing newline character in string returned, while gets not.
update3: way read file indeed fishy. reopen standard input read file - why??? standard practice fopen file, read fscanf , fgets.
update2: stupid (and clever @salil :-). say
it read 'cat'
string[3]
since c arrays indexed 0, string[3] contains 4th line read! third line stored in string[2] - bet contain empty string looking for.
Comments
Post a Comment