-3

我想在我的笔记本电脑(Windows 7)上做一个简单的 toupper 编码。看来我写的任何东西在开头都只大写了一个单词。

我是否使用 %s / %c / %[^\n]

我应该做什么?

我正在使用 Microsoft Visual C++ 2010 Express

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

int main()
{
    char kalimat;
    scanf ("%[^\n]",&kalimat);
    kalimat=toupper(kalimat);
    printf("%s",kalimat);
    getchar ();
    return(0);
}
4

2 回答 2

1

你想读一个字。为此,您需要一个char具有一些预定义大小的数组。所以改变

char kalimat;

char kalimat[64]; /* Can hold 63 chars, +1 for the NUL-terminator */

接下来,您要扫描一个单词。所以改变

scanf("%[^\n]",&kalimat);

scanf("%63s", kalimat);

这里所做的更改是

  1. %s用于扫描单词的用法与用于扫描字符的用法相反%c
  2. 删除与号,因为%s需要 a char*,而不是 a char**or char(*)[64]
  3. 使用长度说明符(此处为 63)以防止缓冲区溢出。

那么,如果你想

  1. 大写数组/单词的第一个字符,使用

    kalimat[0] = toupper(kalimat[0]);
    

    或者

    *kalimat = toupper(*kalimat);
    
  2. toupper将数组中的所有字符大写,对数组的每个索引使用循环调用:

    int i, len; /* Declare at the start of `main` */
    
    for(i = 0, len = strlen(string); i < len; i++) /* Note: strlen requires `string.h` */
        kalimat[i] = toupper(kalimat[i]);
    

但是......你可能需要改变

getchar ();

int c; /* Declare at the start of `main` */
while((c = getchar()) != EOF && c != '\n');

为了防止控制台关闭。


固定代码:

#include <stdio.h>
#include <ctype.h>
#include <string.h> /* For `strlen` */

int main()
{
    int i, len, c;
    char kalimat[64];

    scanf ("%63s", &kalimat);

    /* `*kalimat = toupper(*kalimat);` */
    /* or */
    /* `kalimat[0] = toupper(kalimat[0]);` */
    /* or */
    /* `for(i = 0, len = strlen(string); i < len; i++) 
        kalimat[i] = toupper(kalimat[i]);` */

    printf("%s", kalimat);

    while((c = getchar()) != EOF && c != '\n');
    return(0);
}
于 2015-10-08T09:55:28.403 回答
0

C 库函数:

int toupper(int c);

将小写字母转换为大写

如果要将字符串的所有字母打印为大写:

int i=0;
while(str[i])
{
 putchar (toupper(str[i]));
 i++;
}

但是,对于大写单个字符,您可以简单地使用:

 putchar (toupper(mychar));

如果存在一个或返回发送给它的相同字符,则该函数返回大写。

在 C 中,您可以存储一个字符串:

 char *string1="Elvis";
 char string2[]="Presley";
 char string3[4]="King";
于 2015-10-08T10:08:41.390 回答