使用 fgetc(stdin) 设置变量

Set variables by using fgetc(stdin)

我正在尝试使用 stdin 中的 fgetc() 来设置变量。

到目前为止,这是我的代码,

#include <stdio.h>

int main(void){
    int ch;
    int firstNumber,secondNumber;
    char str;

    printf("Enter two numbers and a string: ");
    while((ch=fgetc(stdin))!='\n'){
        while(ch != ' '){
            firstNumber = ch;
            secondNumber = ch;
            string = ch;
            }
        }
    printf("%d %d %s",firstNumber,secondNumber,string);
    return 0;
}

因此,如果我键入 2 2 string(字符之间有空格)

我希望变量 firstNumber2

secondNumber2

strstring

我认为你的解决方案应该是:

#include <stdio.h>

int main(void){
    int ch;
    int firstNumber=0,secondNumber=0,b=0;
    char str;

    printf("Enter two numbers and a string: ");
    while((ch=fgetc(stdin))!='\n'){
        if (ch != ' '){
            if (b==0)
                 firstNumber = firstnumber*10 + ch-'0';
            else
            if (b==1)
                secondNumber = secondnumber*10 + ch-'0';
            else
                str = ch;
        }
        else b++;
    }
    printf("%d %d %c",firstNumber,secondNumber,str);
    return 0;
}

请注意b 跟踪您分配的内容并打印str,whch 实际上只是一个字符,您需要使用%c。此外,没有要打印的变量 string,只有 str.

以下是可能的方法:

  1. You can parse the entire string first and store it into temporary buffer.
  2. You can now use strtok() to tokenize the string using ' '(space) character. Alternatively, you can use sscanf() instead of strtok().
  3. Use atoi() for first two numbers and read the final string.

代码:

Assuming that the buffer required to store scanned string doesn't exceed 100 bytes.

方法使用strtok():

int main()
{
    int ch,i=0;
    int firstNumber,secondNumber;
    const char seperator[2] = " -";
    char buffer[100];
    char *string;

    printf("Enter two numbers and a string: ");
    while((ch=fgetc(stdin))!='\n'){
        buff[i++]=ch;
    }

    /* get the first token as a number */
    firstNumber = atoi(strtok(buff, seperator));
    printf("%d\n",firstNumber);

    /* get the second token as a number*/   
    secondNumber = atoi(strtok(NULL, seperator));    
    printf("%d\n",secondNumber);

    /* get the third token as a string */
    string=strtok(NULL, seperator);
    printf("%s\n",string);

    return(0);
}

方法使用sscanf():

printf("Enter two numbers and a string: ");
while((ch=fgetc(stdin))!='\n'){
    buff[i++]=ch;
}

sscanf(buff, "%d %d %s", &firstNumber, &secondNumber, string);  
printf("%d\n%d\n%s\n", firstNumber, secondNumber, string);

不需要strtok,我们这里用sscanf也可以实现;

#include <stdio.h>
#include <stdlib.h>

int main()
{
      int firstNumber,secondNumber;
      char str[100];
      char buffer[100];

      printf("Enter two numbers and a string: ");
      fgets(buffer, 1024, stdin);

      sscanf(buffer, "%d %d %s", &firstNumber, &secondNumber, str);
      printf("%d %d %s\n",firstNumber,secondNumber,str);

      return(0);
}

输出

root@viswesn-vm:/var/lib/lxc# ./a.out 

Enter two numbers and a string: 2 234 king

2 234 king