c - C中读取空字符串的方法

标签 c

我在 C 中读取空字符串时遇到问题。我想从以下读取字符串 -

  1. 屁股
  2. (空)

但是当我使用 gets() 时,它不会将 (empty) 视为字符串 [2]。它将“猫”读作字符串[2]。那么我该如何解决这个问题呢?

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;
}

输入看起来像

我在这里给出了代码。输入可能是这样的

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

我希望

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

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




好的,我终于找到问题了。这是行

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

这会在通过 gets() 获取输入时产生问题。而不是使用整数 n1, n2 换行,然后我将换行作为 ("%c",&ch) 然后一切都是好的。

感谢所有回答我的人。

最佳答案

很可能,字符串包含 \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 则没有。

更新 3:您从文件中读取的方式确实有问题。您重新打开标准输入以从文件中读取 - 为什么???标准做法是 fopen文件,然后使用 fscanf 从中读取和 fgets

Update2: 愚蠢的我们(和聪明的@Salil :-)。你说

it read 'cat' as string[3]

由于 C 数组是从 0 开始索引的,string[3] 包含读取的第 4 行!第三行存储在 string[2] 中 - 我打赌它会包含您要查找的空字符串。

关于c - C中读取空字符串的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2743208/

相关文章:

c - 查找数组中输入数字的中位数

c - 为什么在 C 中将\0 定义为 char 数组的第一个元素?

c - 如果新 block 大小小于初始 block 大小,我应该强制执行 realloc 检查吗?

c - 需要有关代码片段的建议

c - 带栅栏的 SPSC 线程安全

c - PRQA : How to ignore some specific files?

c++ - 用于 python 列表的 SWIG typemap to double *

c - C 中的数独解算器无法正常工作

c++ - 如何从主类中调用 C++ 中的函数?

c++ - CUDA cudaMalloc 在运行具有巨大静态数组的内核后失败