c - C 编程中指针字符串不接受输入

标签 c

#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/

相关文章:

c - 基本 C 指针

c++ - 表示命令包格式的数据结构

c - 在Kali Linux中运行时出现段错误-客户端和服务器聊天室

c - 我正在尝试在我的 C 程序登录中应用 do while 循环,但我不明白

c - 正确使用 Char**

c++ - 未使用值警告 : C vs C++ using gcc

c - 使用 switch - C 后简单程序崩溃

c - 带有 char** val 的结构

c++ - Eclipse 中的 C/C++,我可以使用 #define 来设置断点,但只能在单步执行代码时使用吗?

c - C 语言的游戏编程,我从哪里开始?