简体   繁体   English

从C中的多行STDIN读取:分段错误或根本没有读取

[英]Reading from multi-lines STDIN in C : segmentation error or no reading at all

I am trying to read multiple lines from stdin, in which even lines are strings and odd lines are numbers separated by spaces. 我正在尝试从stdin中读取多行,其中偶数行是字符串,奇数行是由空格分隔的数字。 I'm trying to read the numbers as integers and the strings as... strings. 我正在尝试将数字读取为整数,将字符串读取为...字符串。 It's part of a school project but it's not the entire thing; 这是学校项目的一部分,但不是全部。 I managed the rest of the stuff but I can't manage to actually GET the strings and ints from stdin. 我管理了其余的东西,但实际上无法从stdin中获取字符串和整数。

I add every name to experiments when i is even (I try to use it as a line number) I tried using malloc to append a string n and store it as an int in aa 2d array data when I encounter a space, using int a to navigate through the line. 我在偶数时将所有名称添加到实验中(我尝试将其用作行号)我尝试使用malloc追加字符串n并在遇到空格时将其存储为int格式的2d数组数据,使用int a在行中导航。

And then the printing part is just to try to show it works and.. it doesn't. 然后打印部分只是试图显示它的工作原理,而不是。 I'm not busting any array's length and I felt like I watched out for malloc but I spent more than 15 hours on this part and nothing good is coming out of it. 我并没有破坏任何数组的长度,我觉得我很在意malloc,但是我花了超过15个小时来完成这部分工作,但结果并不令人满意。 I wondered if someone could give me a hint. 我想知道是否有人可以给我提示。

 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
int main(int argc, char **argv) {
char *experiments[100];
int data[10][20];
char name[101];
int i=0;
int j=0;
char *n;
char *g;
fgets(name, 100, stdin);
while ((strstr(name,"*** END ***")!=0)&&(name!=NULL)){
    if((i%2)==0){
        experiments[i/2]=name;
        name[0]='\0';
    }
    else {
        int a = 0;
        while ((name[a]!='\n')&&(a<100)){
            if (name[a]!=' '){
                size_t len = strlen(n);
                g = malloc(len + 1 + 1);
                strcpy(g,n);
                g[strlen(n)-2] = name[a];
                g[strlen(n)-1] = '\0';
                n[0]='\0';
                *n = *g;
                free( g );
                a+=1;
            }
            else {
                data[j][i]=*n;
                j+=1;
                n[0]='\0';
                a+=1;

            }
        }
    }
    i+=1;
    fgets(name,100, stdin );
}
int k=0;
for(k=0;k<=i;k+=1){
    printf("printing\n");
    printf("%s\n", experiments[k]);
    if (experiments[k][0]=='\0') {
        printf("oh shoot!");
    }
    }

return(0);}

You seem to have fundamental confusions regarding: 您似乎在以下方面有基本的困惑:

  • Do you know the saying "Give me six hours to chop down a tree and I will spend the first four sharpening the axe"? 您是否知道这样的说法:“给我六个小时砍下一棵树,我会花前四个时间削斧头吗?” There are many problems here, and they're probably caused by a blunt axe. 这里有很多问题,它们可能是由钝斧头引起的。 Whatever book you're using to learn C is failing to teach you. 无论您使用哪本书来学习C,都无法教您。 I recommend K&R 2E. 我推荐K&R 2E。 Don't forget to do the exercises. 不要忘记做练习。
  • Yuck! Neither for nor return are functions! 无论是for还是return的功能! Please, for the love of life, if you want other people to read your code, make it presentable for them! 请热爱生活,如果您想让其他人阅读您的代码,请使其对他人有帮助! It would help if your code were consistently indented, too. 如果您的代码也始终一致缩进,也会有所帮助。
  • Arrays (eg it's impossible for name!=NULL to evaluate false, so that expression is pointless), pointers and the implicit conversion from array to pointer that occurs in experiments[i/2]=name; 数组(例如, name!=NULL不可能计算为false,因此表达式毫无意义),指针以及在experiments[i/2]=name;中发生的从数组到指针的隐式转换experiments[i/2]=name; . To clarify, every time you assign like that, the different elements will point to the same place, and the values stored within that place will be overwritten when you next call fgets . 需要说明的是,每次这样分配时,不同的元素将指向同一位置,并且在您下次调用fgets时,该位置中存储的值将被覆盖。
  • malloc ; malloc ; you've used it in the wrong place, and the way you used it reinvents automatic storage duration (that is, all of your variables). 您在错误的位置使用了它,并且使用它的方式重新发明了自动存储持续时间(即所有变量)。 You might as well just not use it at all. 您可能根本不使用它。
  • fgets ; fgets ; its mode of failure leads to horrible crashes in your program. 它的失败模式会导致程序崩溃。
  • Strings; 弦; see above. 往上看。

Start by reading K&R 2E and doing the exercises as I mentioned earlier... Once you've completed that book I reckon you'll have a fine chance at filling in the blanks for this program: 首先阅读K&R 2E并按照我之前提到的方法进行练习...完成这本书后,我认为您将有很好的机会填补该程序的空白:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv) {
    char *experiments[100] = { 0 };
    int data[10][20] = { 0 };
    char name[101] = { 0 };
    size_t i = 0, j = 0;
    fgets(name, sizeof name, stdin);
    while (strstr(name,"*** END ***") != 0){
        if(i%2 == 0){
            experiments[i / 2] = malloc(strlen(name) + 1);
            if (experiments[i / 2] == NULL) {
                puts("OOPS! malloc failure!");
                return 0;
            }
            strcpy(experiments[i / 2], name);
        }
        else {
            /* XXX: I have no idea what any of this was meant to do *
             * ...  but it was all HORRIBLY WRONG so I removed it.  *
             *      Try again once you've read K&R 2E and done the  *
             *      exercises...                                    */
        }
        i++;
        fgets(name, sizeof name, stdin);
    }

    for (size_t k = 0; k < i / 2; k++){
        puts("Printing...");
        puts(experiments[k]);
        if (experiments[k][0] == '\0') {
            puts("oh shoot!");
        }
        free(experiments[k]);
    }

    return 0;
}

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

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