【问题标题】:how to access a character in an array of strings in c如何在c中访问字符串数组中的字符
【发布时间】:2021-08-01 13:30:07
【问题描述】:

我一直在尝试将字符串数组中的字符串的第一个字母大写我尝试了很多方法,但我的代码在这里都不起作用:

 #include <stdio.h>
 #include <stdlib.h>
 int nw=0;
 char words[30][50];
 int main(){
 printf("enter your words when you finish write b\n");
 do{
 nw++;
 scanf("%s",&words[nw]);
 }while(strcmp(&words[nw],"b")!=0);
 printf("%s",toupper(&words[1][0]));
 }

我该怎么办,请帮忙

【问题讨论】:

  • 你应该正确缩进你的代码。
  • 数组从索引 0 开始。

标签: arrays c char c-strings toupper


【解决方案1】:

对于初学者,您需要包含标题 &lt;ctype.h&gt; 和 &lt;string.h&gt;

#include <ctype.h>
#include <string.h>

声明这些变量没有太大意义

int nw=0;
char words[30][50];

在文件范围内。它们可以在main 中声明。

而不是这个调用

scanf("%s",&words[nw]);

你至少要写

scanf("%s", words[nw]);

do-while 语句中的条件应该是这样的

while( nw < 30 && strcmp(words[nw],"b") != 0 );

而不是这个电话'

printf("%s",toupper(&words[1][0]));

你应该写

words[1][0] = toupper( ( unsigned char )words[1][0] );
printf( "%s", words[1] );

这是一个演示程序。

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    char words[30][50] =
    {
        "hello", "world!"
    };
    
    for ( size_t i = 0; words[i][0] != '\0'; i++ )
    {
        words[i][0] = toupper( ( unsigned char )words[i][0] );
        printf( "%s ", words[i] );
    }
    putchar( '\n' );
    
    return 0;
}

程序输出是

Hello World!

【讨论】:

    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多