简体   繁体   English

C:字符数组的索引并使用strcmp

[英]C: Indexing of character arrays and using strcmp

I accidentally ran expensive simulations with an extra printf statement hidden in a for loop, creating huge ~10 GB files instead of ~10 KB files. 我不小心运行了昂贵的模拟,在for循环中隐藏了一个额外的printf语句,从而创建了大约10 GB的文件,而不是大约10 KB的文件。

Re running the simulations isn't the best option so I've decided to take a crack at fixing the problem even though I don't have any formal training with C. 重新运行模拟不是最好的选择,因此即使我没有接受过C的正式培训,我还是决定努力解决问题。

I'm trying to fix the problem by creating a program that reads these huge files, and prints out only the lines of the form (x, y, t, n) where (x, y, t, n are int, int, long double, long double). 我正在尝试通过创建一个程序来解决这些问题,该程序可以读取这些大文件,并且仅打印出(x,y,t,n)形式的行,其中(x,y,t,n为int,int,长双,长双)。 The other lines are a combination of strings, numbers and spaces that basically describe certain parameters, but all the (millions) of unwanted lines start with the letter "i". 其他行是基本描述某些参数的字符串,数字和空格的组合,但是所有(百万)行不需要的行都以字母“ i”开头。

So I thought I'd try to follow the example of this code here: Skip a line while reading a file in C 因此,我认为我将尝试在此处遵循此代码示例: 在C语言中读取文件时跳过一行

int main(int argc, char *argv[])
{
     FILE *f;

     if((f = fopen(argv[1], "r")) == NULL)
     {
         printf("Couldn't open file. \n");
         return(0);
     }

     char buf[500];

     while(fgets(buf, sizeof(buf), f) != NULL)
     {

         if(strcmp(&buf[0], "i") != 0)
         {
             printf("%s \n", buf);
         }

     }
}

So it seems the line 所以似乎线

if(strcmp(&buf[0], "i") != 0)

Doesn't really work, as even if the first element of a line is "i" the printf of the line still prints. 即使行的第一个元素为“ i”,该行实际上也不会打印,实际上并不能工作。 Interestingly if I add this inside the if statement: 有趣的是,如果我在if语句中添加它:

printf("%c \n", buf[0]);

"i" can still print, even though I was trying to make that the condition for failing the if statement. 即使我试图使if语句失败的条件,“ i”仍然可以打印。 Interestingly, the line 有趣的是,线

printf("%s \n", &buf[0]);

Just prints the same thing as 只是打印与

printf("%s \n", buf);

I tried to re-write 我试图重写

if(strcmp(&buf[0], "i") != 0)

as

if(strcmp(buf[0], "i") != 0)

but just received an error. 但刚刚收到一个错误。

How do I correctly compare the first element of each line to a chosen character "i"? 如何正确比较每行的第一个元素和所选字符“ i”?

you can use strncmp() instead of strcmp() for comparing the n elements of string. 您可以使用strncmp()而不是strcmp()来比较字符串的n个元素。

if statement should be like if((strncmp(buf,"i",1))!=0) .Now it will compare only one element ie the 1st element of string stored in buf to i . if语句应该类似于if((strncmp(buf,"i",1))!=0) 。现在它将只比较one元素,即存储在buf的字符串的1st one元素与i

But for first element you can simply use if(buf[0]=='i') . 但是对于第一个元素,您可以简单地使用if(buf[0]=='i')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM