C语言 如何从二维字符串中访问字符

xytpbqjk  于 2023-01-08  发布在  其他
关注(0)|答案(2)|浏览(115)
#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
    register int i;
    printf("Enter an empty line to quit\n");
    for(i =0 ;i<max;i++){
        gets(text[i]);
        if(!*text[i]){break;}
    }
puts(text[1][0]);/*I want to display first character of second string but it doesn't print anything. Why??*/
}

如何从字符串数组中访问字符或字符串一部分

mm9b1k5b

mm9b1k5b1#

对于符合C标准的启动器,不带参数的函数main应声明如下

int main( void )

函数gets不安全,C标准不支持。请改用标准C函数fgets
函数puts需要一个指针类型为char *的参数,该参数指向一个字符串。但是,您传递的对象类型为char

puts(text[1][0]);

会引发未定义的行为。
同时在变量使用的最小作用域中声明变量,在文件作用域中声明数组text没有多大意义。
该程序可以如下所示

#include <stdio.h>

#define MAX 50
#define LEN 30

int main( void )
{
    char text[MAX][LEN] = { 0 };

    puts( "Enter an empty line to quit" );

    size_t i = 0;

    while ( i < MAX && fgets( text[i], LEN, stdin ) != NULL && text[i][0] != '\n' ) 
    {
        ++i;
    }

    if ( !( i < 2 ) ) printf( "%c\n", text[1][0] );
}

注意,函数fgets可以将新的行字符'\n'存储在提供的数组中。
如果你想删除它,你可以写

#include <string.h>

//...

text[i][ strcspn( text[i], "\n" ) ] = '\0';
nc1teljy

nc1teljy2#

在您的代码中,puts(text[1][0])试图打印text[1][0],而text[1][0]char,而puts只接受char*,这导致我的计算机上出现分段错误。
但是,printf允许您打印char
固定代码:

#include <stdio.h>
#include <string.h>
#define max 50
#define len 30
char text[max][len];
void main(){
    register int i;
    printf("Enter an empty line to quit\n");
    for(i =0 ;i<max;i++){
        gets(text[i]);
        if(!*text[i]){break;}
    }
printf("%c\n", text[1][0]); /* printf allows you to print char */
}

注意:正如问题注解中所述,您也可以使用putchar()打印一个字符。
输入:

s
s

输出:

s

相关问题