我如何接受用户输入的内容,其中包括由空格分隔的字符串和整数?

问题描述 投票:-1回答:1

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

用户仅以以下形式输入:

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

首先,仅输入字符串,后面没有整数在第二个中,字符串和一个整数跟随在第3个中,跟随两个整数]

要求:我想将字符串保存到变量“输入”,将整数保存到变量“ 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;
}

上面的代码有问题:如果用户输入,它将失败

mystring(OR)

mystring 100

c input syntax scanf
1个回答
0
投票

我的方法如下:1.将这整个作为一个输入字符串,即mystring 100100(或)mystring 100(或)mystring2.使用strtok关键字用“空格”分隔字符串3,维护一个变量count,如果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) ; 
© www.soinside.com 2019 - 2024. All rights reserved.