首页 > 解决方案 > 如何在c中使用while循环将字符串值存储在数组的特定索引中

问题描述

我想使用 while 循环将字符串值存储在字符数组的特定索引处。

while 循环终止的条件:应按下“q”以停止输入

到目前为止我的代码

  char s[100],in;
  int count = 0;
  printf("Enter individual names: \n");
  scanf("%c",&in);
   
  while (in != 'q')
  {
    s[count++] = in;
    scanf("%c", &in);
  }
  printf("%d", count);
  printf("%s" , s);

输入 :

    sam 

    tam 

    q

输出 :

    9����

我不明白如何将字符串存储在数组的单个索引处,以及为什么 count 在应该为 2 时给了我错误的值。

还有其他使用while循环存储字符串的方法吗?

太感谢了。

标签: arrayscstringwhile-loopscanf

解决方案


问题是您正在扫描单个字符而不是字符串。tam 和 sam 是 3 个字符,而不是一个。您需要将代码修改为类似这样的内容,将输入字符串读入输入缓冲区,然后将其复制到您拥有的 s 缓冲区中。

编辑:对不起,我误解了你的问题。这应该做你想要的。如果您对此有任何疑问,请告诉我。

#include <stdio.h> // scanf, printf
#include <stdlib.h> // malloc, free
#include <string.h> // strlen, strcpy

#define MAX_NUM_INPUT_STRINGS 20

int main(int argc, char **argv) { // Look no further than our friend argv!
    char* s[MAX_NUM_INPUT_STRINGS], in[100]; // change in to buffer here, change s to char pointer array
    size_t count = 0, len;
    printf("Enter individual names: \n");
    do {
        scanf("%s",in);
        size_t len = strlen(in);
        if (in[0] == 'q' && len == 1) {
            break;
        }
        // allocate memory for string
        s[count] = malloc(len + 1); // length of string plus 1 for null terminating char
        s[count][len] = '\0'; // Must add null terminator to string.
        strcpy(s[count++], in); // copy input string to c string array
    } while (count < MAX_NUM_INPUT_STRINGS); // allows user to enter single char other than 'q'
    printf("Count: %lu\n", count);
    for (size_t i = 0; i < count; i++) {
        printf("%s\n", s[i]);
    }

    // free allocated memory
    for (size_t i = 0; i < count; i++) {
        free(s[i]);
    }
    return 1;
}

推荐阅读