繁体   English   中英

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

[英]How do I take input from a user that includes a string and integer separated by white space?

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

用户只输入以下形式:

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

我的方法如下:
1.Take the whole this an input string 即 mystring 100 100 (or) mystring 100 (or) mystring
2.使用strtok关键字通过“空白”分割字符串
3.维护一个变量计数,
如果 count 为 1 且 count 为 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) ; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM