Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用scanf函数打印字符串的第n项?_C_String_Pointers_Char_C Strings - Fatal编程技术网

如何使用scanf函数打印字符串的第n项?

如何使用scanf函数打印字符串的第n项?,c,string,pointers,char,c-strings,C,String,Pointers,Char,C Strings,用户输入字符串后,控制台将不会执行任何操作 我已经得到了使用char string=enteraword并取出整个printf和scanf函数的代码,但是我需要使用scanf函数的代码 #include <stdio.h> #include <string.h> int main() { char* string; printf("Enter a word: "); scanf("%s", string); char c=string[1]; pri

用户输入字符串后,控制台将不会执行任何操作

我已经得到了使用char string=enteraword并取出整个printf和scanf函数的代码,但是我需要使用scanf函数的代码

#include <stdio.h>
#include <string.h>

int main()
{
  char* string;
  printf("Enter a word: ");
  scanf("%s", string);
  char c=string[1];
  printf("The second letter in %s is %c", string, c);
  return 0;
}

这段代码有未定义的行为,您正在向scanf传递一个未初始化的指针,要求它在那里存储一个字符串

另外,请记住%s将停止在空白处,因此这里的术语含义非常不清楚

试试看,例如:

char string[1024];
if(scanf("%1023s", string) == 1 && string[0] != '\0')
{
  const char c = string[1];
  printf("The second letter of '%s' is '%c'\n", string, c);
}

您有一个指针字符串,但它指向哪里?C没有任何类型的动态数组;to char*string=malloc10@邢,谢谢它成功了:@nicomp-True,我相信并编辑了它。甚至测试都在ideone上运行了我的代码。谢谢