arrays - 如何在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循环存储字符串的方法吗?
太感谢了。
解决方案
问题是您正在扫描单个字符而不是字符串。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;
}
推荐阅读
- java - 从 javafx 中的可编辑单元工厂获取输出
- php - 在访问器中覆盖 Laravel Eloquent 模型在使用属性时返回 0
- ruby-on-rails - 在 Rails 中为更简洁的 URL 自定义嵌套路由?
- c++ - 获取函数返回的一些垃圾
- segmentation-fault - 在 runc 容器中执行二进制文件时出现分段错误
- javascript - 如果 Promise 中有一个空对象,则停止执行 Await 的方法,但不应返回错误并执行其他任务
- ios - OpenGL 在 IOS 12 中已弃用,如何在 ios 12+ 设备上安全地继续使用 openGL?
- python - Pandas:Groupby 并在组内使用条件进行迭代?
- powershell - 使用 Powershell 在虚拟机上远程运行可执行文件
- android - 为什么 Android Studio 3.1.4 出现渲染问题?