C语言 如何使用while循环将字符串值存储在数组的特定索引中



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

while循环终止的条件:按下'q'停止接受输入

My Code so far

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����

我不明白我怎么能把字符串存储在数组的单独索引上,为什么计数给我错误的值,而它应该是2。

是否有其他方法来存储字符串使用while循环?

问题是您正在扫描单个字符而不是字符串。Tam和Sam是三个角色,而不是一个。你需要把你的代码修改成这样,把输入字符串读入一个输入缓冲区,然后把它复制到你的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] = ''; // 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: %lun", count);
for (size_t i = 0; i < count; i++) {
printf("%sn", s[i]);
}
// free allocated memory
for (size_t i = 0; i < count; i++) {
free(s[i]);
}
return 1;
}

C-strings需要在末尾添加一个'',而不能在s上添加一个。

printf("%d", count);
s[count] = ''; // ADD THIS LINE
printf("%s" , s);

但是你也可以这样读:

char s[100];
scanf("%99[^q]" s); // Will read up to 99 chars that are not a 'q'
printf("%sn", s);
int count = strlen(s);

最新更新