简体   繁体   English

从 C 中的字符串数组中获取单个字符

[英]Getting a single character out of a string array in C

Let's say that i have an array of strings that looks like this: Alphabet As you can see, this is the alphabet represented with #.假设我有一个看起来像这样的字符串数组: Alphabet正如你所看到的,这是用# 表示的字母表。 The aim of the program is to show a letter (that comes from an input) using #.该程序的目的是使用 # 显示一个字母(来自输入)。

So if input = E , i will have to print E所以如果 input = E ,我将不得不打印E

If a letter is not beetwen [az] or [AZ], i have to print a question mark(made with #).如果一个字母不是 beetwen [az] 或 [AZ],我必须打印一个问号(用 # 制作)。 We are given T: the message to code H: the height of the letter(number of rows), L: the lenght of letters, and ROW:the sequence of rows that create the alphabet with #.我们得到 T:要编码的消息 H:字母的高度(行数),L:字母的长度,以及 ROW:用 # 创建字母表的行序列。

So i actually got a part of the program already coded.所以我实际上得到了已经编码的程序的一部分。 But my problem is not how to sort this out.但我的问题不是如何解决这个问题。 The fact is that i've just learned pointers(basic use) and i don't understand how to handle them in a more complex(for me, it's complex), way.事实是,我刚刚学习了指针(基本使用),我不明白如何以更复杂的方式(对我来说,它很复杂)来处理它们。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/
int main()
{
    int L;
    scanf("%d", &L); fgetc(stdin);
    int H;
    scanf("%d", &H); fgetc(stdin);
    char T[257];
    fgets(T, 257, stdin);

    char elements[H][sizeof(T)];
    char *pointer, *Pelements[H];

    pointer = T;

    for (int i = 0; i < H; i++) {

        char ROW[1025];
        fgets(ROW, 1025, stdin);
        // given by the program

        strcpy(elements[i], ROW);
        Pelements[i] = &elements[i];
        // now i got the address of every first character of a string
    }

    while(*pointer != '\0'){
      if(*pointer >='a' && *pointer <= 'z' || *pointer >='A' && *pointer <= 'Z'){
        int temp= ((*pointer) - 'A');
        if(temp <= 25){
          for(int i=0; i<H; i++){
            int index= temp*L; // getting the position where to start to print
            for(int j=0; j<L; j++){
              printf("%s " , *Pelements+index);
              Pelements[i]++; //could have used index++
            }
          }
        }
      }
      else{
          printf("?");
      } 
      pointer++;
    }
    return 0;
}

The program is not completed ( i didn't handle [az]) in fact i'm testing it only with uppercase letters.程序没有完成(我没有处理 [az])实际上我只是用大写字母测试它。

THE PROBLEM: It keeps returning "segmentation fault", or giving me # in random positions.问题:它不断返回“分段错误”,或者在随机位置给我#。 Thank you in advance.先感谢您。

If I have understood what are you trying to accomplish, most of your code is pretty useless.如果我已经了解您要完成的任务,那么您的大部分代码都毫无用处。 This:这个:

#include <stdio.h>
#include <stdlib.h>

#define BUFSIZE 128

int main()
{

    char *ROW[5] = {
        " # ##  #### ###### ### #### ### ##  # #### # ##  # ##  ###### ## ## ## ## #######   ",
        "# ## ##  # ##  #  #  # # #   ## ##  #### ## ## ## ## ##   # # ## ## ## ## #  #  #   ",
        "##### #  # ### ## # #### #   ### #  #### ## ### # ###  #  # # ## #### #  #  #  ##   ",
        "# # ###  # ##  #  # ## # # # ## ##  # ## ## ##   ### #  # # # ## ##### # # #        ",
        "# ###  #### ####  #### #### # # ##### ## # # #    ## ###  # ### # # ## # # ### #    ",
    };
    const int L = 3;  // why do you want to read those from stdin?
    const int H = 5;  // they depend on how you define your alphabet
    const int not_a_letter = 26; // "index" of ? in your alphabet
    const int space = 27;           // I added a space
//    char T[BUFSIZE];
//    fgets(T, BUFSIZE, stdin);
    char T[]= "Hello World!"; //better starting with something short. note what happens to the '!'
    for( int i = 0; i < H; i++) { // for every row
        char  * pch = T;
        int temp;
        while( *pch != '\0') {
            if( *pch >='A' && *pch <= 'Z' ) temp = *pch - 'A';
            else if ( *pch >='a' && *pch <= 'z') temp = *pch - 'a'; // I'll print only capitals...
            else if ( *pch == ' ') temp = space;
            else temp = not_a_letter;
            int index = temp * L; 
            printf("%.*s " , L, ROW[i]+index); // print L char of string ROW[i] starting from index
            pch++;
        }
        printf("\n");
    }

    return 0;
}

Will print this:将打印这个:

# # ### #   #    #      # #  #  ##  #   ##  ###
# # #   #   #   # #     # # # # # # #   # #   #
### ##  #   #   # #     ### # # ##  #   # #  ##
# # #   #   #   # #     ### # # # # #   # #
# # ### ### ###  #      # #  #  # # ### ##   #

edit:编辑:

I'd like to add some considerations.我想补充一些注意事项。 Your program's input is read from stdin.你的程序的输入是从标准输入读取的。 This is a requirement, I guess, as most on line compiler redirect input and output from files, but it's not really convenient to enter every time all the variables, expecially all those "## #### ###...", so I hard coded them in the program.我猜这是一个要求,因为大多数在线编译器重定向文件的输入和输出,但是每次输入所有变量时都不太方便,尤其是所有那些“## #### ###...” ,所以我在程序中对它们进行了硬编码。 I didn't add extra spaces between the letters so my L is 3, but in the picturre you posted they did, so your L is 4.我没有在字母之间添加额外的空格,所以我的 L 是 3,但在你发布的图片中,他们做了,所以你的 L 是 4。

You can keep that part of your program unchanged (mostly), but I'd like to point out a couple of things.您可以保持程序的那部分不变(大部分),但我想指出一些事情。 When you read T you allocate enough space for 256 char, usually consolle screen are ~80 column wide so a string greater then 20 characters ( 80/4 ;) will be messed up when printed on stdout unless the output is redirected to a file (probably) or you change the program so that it can print out from T only 20 char at a time.当您读取 T 时,您会为 256 个字符分配足够的空间,通常控制台屏幕大约为 80 列宽,因此在 stdout 上打印时,大于 20 个字符( 80/4 ;)的字符串将被弄乱,除非将输出重定向到文件(可能)或者您更改程序,以便它一次只能从 T 打印 20 个字符。 Then you read the "font" using a buffer (ROW) big enough to contain 256 magnified characters (256*4=1024 ;) which is the entire ASCII set.然后,您使用足够大的缓冲区 (ROW) 读取“字体”,该缓冲区足以包含 256 个放大字符 (256*4=1024 ;),这是整个 ASCII 集。 I used only the capital letters, of course, but the problem is that IF they give you ALL the character you don't need a temp variable to shift the index to the right range, otherwise you don't need all that space.当然,我只使用了大写字母,但问题是如果它们给你所有的字符,你不需要临时变量来将索引移动到正确的范围,否则你不需要所有的空间。 You should check what's the case.你应该检查一下是什么情况。 You can read directly into ROW after having allocated the memory:分配内存后,您可以直接读入 ROW:

#define BUFSIZE 1025

char **ROW = malloc(H*sizeof(char*));
for (int i = 0; i < H; i++) {

    ROW[i] = malloc(BUFSIZE);
    fgets(ROW[i], BUFSIZE, stdin);

}

Remember to free the memory before closing the program:记得在关闭程序之前释放内存:

for (int i = 0; i < H; i++) {
    free(ROW[i]);
}
free(ROW);

I think your problem is here :我认为你的问题在这里:

int index = temp*L; 

From your code temp can be up to 25 and in your input in L is for instance the char A (64), your index will be 1600 which is I think larger than your Pelements size.从您的代码temp可以达到 25,并且在L中的输入是例如字符A (64),您的索引将为 1600,我认为这比您的Pelements大小大。

I can not tell if this will solve your whole problem, but it might make you resolve a first issue.我不知道这是否能解决你的整个问题,但它可能会让你解决第一个问题。

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

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