读取用户的输入

时间:2014-10-11 09:15:18

标签: c user-input scanf

如何阅读数字&amp;包含字符和数字的输入字符串中的字符使用scanf? 例如,如果输入是 Fox 2 5 ,我得到F,2,5,如果它是 Box 11 21 ,我得到B,11,21,我尝试使用< strong> scanf(“%cox%d%d”,&amp; s,&amp; t,&amp; u)但它不起作用。 我还尝试了 scanf(“%[^ \ n] s”,&amp; c)并使用(char)c [0],c [4],c [6];但没有成功。

编辑 - 我原来的方法是正确的,我在dev c ++中遇到了一个小故障当我在代码块中运行它运行得很好

1 个答案:

答案 0 :(得分:1)

我们假设您有以下输入格式:

字符串编号\ n

#include "stdio.h"

int main()
{
   char string[100];
   int a, b;
   scanf("%99s %d %d",string , &a, &b);
   printf("The string is:\t%s\n",string);
   printf("The first int is:\t%d\n",a);
   printf("The second int is:\t%d\n",b);
   return 0; 
}

如果您希望数字为浮点数,则应将%d更改为%f。 另请注意,我假设字符串的最大大小为100个字符(将其更改为您认为合乎逻辑的任何字符)。

如果您只想阅读第一个字符并忽略字符串中的其余字符,则可以执行以下操作:

#include "stdio.h"

int main()
{
   char character;
   int a, b;
   scanf("%c%*s %d %d",&character , &a, &b);
   printf("The string is:\t%s\n",character);
   printf("The first int is:\t%d\n",a);
   printf("The second int is:\t%d\n",b);
   return 0; 
}
相关问题