How to read an empty string in C

I have a problem reading an empty line in C. I want to read a line from the following -

  • ass
  • ball
  • (empty)
  • cat

but when I use gets()it does not treat (empty)as a string [2]. It reads "cat" as a string [2]. So how can I solve this 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 is the necessery part
        scanf("%d %d\n",&n1,&n2);
        count = 0;

        printf("n1=%d n2=%d\n",n1,n2);
        for(i = 0; i < n1; i++)
        {
          gets(str1[i]);
        }

        for(i = 0; i < n2; i++)
        {
            gets(str2[i]);
        }

        //end of reading input

        for(i = 0; i < 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 the input may look like

I have provided the code here. Entrance can be like

line1>1
line2>3 3
line3>(empty line)
line4>a
line5>b
line6>c
line7>(empty)
line8>b

And i expect

str1[0]=(empty).
str1[1]=a;
str1[2]=b;

and

str2[0]=c;
str2[1]=(empty);
str2[2]=b;




OK, finally I found the problem. This is a string

printf("n1=%d n2=%d\n",n1,n2);

which creates a typing problem gets(). Instead of taking a new line with a number n1, n2I take as a new line ( "%c",&ch), and then everything is in order.

Thanks to everyone who answered me.

+3
source share
4 answers

, \r\n\0 ( \n\r\0 - , ). \r\n ​​Windows, \0 .

, \r \n, . FWIW :

char* string;
// initialize string and read something into it
if (strlen(string) == 0 || string[0] == `\r` || string[0] == `\n`)
  // string is empty

: , gets . fgets, . , fgets , gets - .

Update3: , , . - ??? fopen , fscanf fgets.

Update2: ( @Salil:-).

"cat" string[3]

C 0, string[3] 4- , ! string[2] - , , .

+3

:

#include <cstdio>

int main ()
{
    int i = 0;

    char string [256];
    while (gets(string)) {
        ++i;
    }
    printf("%d\n", i);

    return 0;
}

a
b

d

4

, gets() , , , , . .

+2

, get!!!!! , , gets() . fgets() getchar().

map < string, int > , , ++. ++ iostreams .

, , , ... - , , - , "any <, > ". fgets() , .

+1

, ?

, :)

== ==

OK:

"gets() stdin , s, , EOF, '\ 0'."

, , :

char x [3];

();

x [0] '\ 0'

If you read the man page, you will see that receiving is not recommended. Use fgets instead

0
source

Source: https://habr.com/ru/post/1743470/


All Articles