【问题标题】:How do I take input from a user that includes a string and integer separated by white space?如何从包含空格分隔的字符串和整数的用户那里获取输入?
【发布时间】:2020-02-09 10:21:58
【问题描述】:

如何从用户那里获取包含由空格分隔的字符串和整数的输入?

用户只输入以下形式:

string1 999 1001

其中 string1 可以是长度不超过 100 的任何字符串 它后面的整数可以是 1 到 10^9 之间的任何整数,字符串后面的整数个数可以是 1 或 2

我可以拥有

Ok see my code, but is basically useless. 
My problem is that the user enters inputs in following form

string1 
string2 100
string3 100 200

首先,只输入字符串,后面没有整数 在第二个,字符串和一个整数跟随它 第三个,后面跟着两个整数

要求:我想将字符串保存到变量“input”,将整数保存到变量“num1”、“num2”,因为我需要稍后执行这些操作。

如何在 C 中做到这一点? 几天以来我一直在努力解决这个问题,请帮助

我的代码

#include<stdio.h>

int main()
{
    int p, q;
    char input[100];

    printf("\nEnter:\n");
    scanf("%s %d %d", input, &p, &q);
    printf("%s and %d and %d", input, p, q);

    return 0;
}

上面代码的问题:如果用户输入会失败

我的字符串(或)

我的字符串 100

【问题讨论】:

  • 请展示您尝试过的内容以及您在尝试中遇到的问题。您已经使用了scanf 标签,所以我假设您尝试使用它。为什么你不能让它与scanf一起工作?
  • 主要问题是字符串后面的整数个数可以变化
  • 所以只需循环调用scanf。再次,请显示您尝试过的代码。
  • 我不确定你在说什么。每个scanf 调用可以消耗部分或全部输入的输入。例如,您可以使用scanf("%s") 来读取第一个字符串。之后,输入缓冲区仍将包含下一个整数。然后,您可以在循环中调用scanf("%d"),直到它返回 0 或读取到预期的整数个数。
  • 你知道 scanf 有一个返回值,不是吗?您的代码(就像大多数存在 scanf 问题的代码一样)不明智地忽略了它,但如果没有,您肯定会阅读 en.cppreference.com/w/c/io/fscanf,请参阅我提供的其他链接。

标签: c input syntax scanf


【解决方案1】:

我的做法如下:
1.将整个作为输入字符串,即 mystring 100 100 (or) mystring 100 (or) mystring
2.使用strtok关键字
通过“空格”分割字符串 3.维护一个变量计数,
如果计数为 1 且计数为 2,则类型转换为整数和 将其存储到各自的变量中。 `

// CODE
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
char str[] = "mystring 130 102";
char *token = strtok(str, " "); 
char *mystring =token ; 

int count = 0 ;

while (token != NULL) 
{ 
    if(count == 1 )
      num1 = atoi(token);
    if(count == 2) 
      num2 = atoi(token) ; 
    token = strtok(NULL, " "); 
    count++ ;
} 
printf("%s\n" , mystring);
printf("%d\n" , num1) ; 
printf("%d\n" , num2) ; 

return 0; 

编辑
根据下面的评论,我们仍然可以使用 sscanf() 来降低复杂度

char *mystring = "mystring 102 293";
char str[20] ; 
int num1, num2[100];
strcpy( dtm, "mystring 102 293" );
sscanf( dtm, "%s  %d  %d", str, &num1, &num2 );
printf("%s\n" , mystring);
printf("%d\n" , num1) ; 
printf("%d\n" , num2) ; 

【讨论】:

  • 为什么要使用 strtok()atoi(),但会带来相关的复杂性和问题,而您可以只使用 sscanf()
猜你喜欢
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多