【问题标题】:How to read a user input string and store it in an Array如何读取用户输入字符串并将其存储在数组中
【发布时间】:2013-11-03 02:25:25
【问题描述】:

尝试从键盘读取用户输入字符串并将其分配给数组。 它仍然令人困惑。

还有任何想法 char ch = 97 在这个程序中是什么? 谢谢。

#include<stdlib.h>

int main()
{
    int i = 0;
    int j = 0;
    int count[26]={0};
    char ch = 97;
    char string[100]="readmenow";

    for (i = 0; i < 100; i++)
    {
         for(j=0;j<26;j++)
         {
              if (tolower(string[i]) == (ch+j))
              {
                   count[j]++;
              }
         }
    }
    for(j=0;j<26;j++)
    {
        printf("\n%c -> %d",97+j,count[j]);
    }
}

【问题讨论】:

  • char ch = 97; -- 97 是 'a' 的 ASCII。

标签: c arrays string input keyboard


【解决方案1】:

要读取用户输入,请执行以下操作:

  #include <stdio.h>  // for fgets
  #include <string.h> // for strlen

  fgets(string,sizeof(string),stdin);
  string[strlen(string)-1] = '\0'; // this removes the \n and replaces it with \0

确保包含正确的标题

还有ch= 97;和ch = 'a';一样

编辑:

scanf 非常适合将输入作为字符串读取,只要字符串没有空格即可。 fgets 好多了

编辑 2

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

int main(){

    int i=0,j=0;

    char input[50]; // make the size bigger if you expect a bigger input

    printf("Enter string = ");
    fgets(input,sizeof(input),stdin);
    input[strlen(input)-1] = '\0';

    int count[26]={0};

    for (i = 0; i < strlen(input); i++)
    {
         for(j=0;j<26;j++)
         {
              if (tolower(input[i]) == ('a'+j))
              {
                   count[j]++;
              }
         }
    }
    for(j=0;j<26;j++)
    {
        printf("\n%c -> %d",'a'+j,count[j]);
    }


    return 0;
}

输出: $ ./测试

Enter string = this is a test string

a -> 1
b -> 0
c -> 0
d -> 0
e -> 1
f -> 0
g -> 1
h -> 1
i -> 3
j -> 0
k -> 0
l -> 0
m -> 0
n -> 1
o -> 0
p -> 0
q -> 0
r -> 1
s -> 4
t -> 4
u -> 0
v -> 0
w -> 0
x -> 0
y -> 0
z -> 0

【讨论】:

  • 感谢 ch = 97 现在被清除了。当从键盘读取用户输入字符串时,我们不能使用 scanf ???
  • 好的..我想做的是..在上面的程序中添加代码行以从键盘读取输入并分配给字符串数组并显示结果。例如,当我输入“你今天好吗”时,只需将其分配给该数组并计算并显示其中的每个字符。感谢您的帮助。
  • @Asanka'cj'Munasinghe 查看编辑.. 如果它对你有帮助.. 请投票并接受答案
  • 嘿,伙计,太好了.. 试过了,但我很难得到像我之前发布的代码那样的输出.. 我想读取键盘输入字符串,将其存储在数组中并给出这样的输出 a - 1 b - 0 c - 0 d - 0 e - 2 等等等等。而不是将字符串硬编码到聊天字符串中 [100]="readmenow" 需要从键盘获取并显示像这样的结果..谢谢队友
  • 老兄,我不知道你在找什么......你想要'a'中每个字符的区别吗?还是您想要每个字母在该字符串中出现的次数?
【解决方案2】:
 char ch= 97

意思是ch='a'
它使用 ASCII(美国信息交换标准代码)

【讨论】:

  • 如果你使用"ch=ch+3",它会打印'd'。
猜你喜欢
  • 1970-01-01
  • 2013-09-23
  • 2014-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 2015-10-03
  • 1970-01-01
相关资源
最近更新 更多