#include<stdio.h>
int main()
{
int w,p;
char *name[1000];
for(w=0; p!=2; w++)
{
printf("Add a name: ");
gets(name[w]);
printf("Want to add another one?\n1 for yes\n2 for no\n");
scanf("%d",&p);
}
}
此代码不起作用。如果我写: char *name[3]={"米切尔·约翰逊", "米切尔·斯塔克", "史蒂文·史密斯"}; 然后就可以了。但我想将字符串作为输入。不想定义它。 但控制台框在输入 1 个字符串后停止工作。怎样做才正确呢?请帮忙。谢谢。
最佳答案
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int w = 0;
int ret = 0;
int p = 1;
char line[1024];
char **tab = (char**)malloc(1000*sizeof(char*));
for(w=0; p==1; w++)
{
printf("Add a name: ");
ret = read(0, &line, 1024);
line[ret] = 0;
printf(line);
tab[w] = strdup(line);
printf("Want to add another one?\n1 for yes\n2 for no\n");
scanf("%d",&p);
}
}
这应该可以满足您的要求。但实在是太丑了。
关于c - C 编程中指针字符串不接受输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42978501/