【问题标题】:Using spaces while taking integers from the user [duplicate]从用户那里获取整数时使用空格[重复]
【发布时间】:2022-01-15 11:40:16
【问题描述】:

我正在尝试练习一些关于文本文件、打印和读取文本文件的内容。我需要从用户那里获取输入 - 也许是他们的电话号码或其他人的 - 但我希望他们能够在数字之间使用空格

假设我的电话号码是:565 856 12 我希望他们能够给我这个带空格的号码,而不是像 56585612

这样的压缩版本

到目前为止,我已经尝试了 scanf(),但我不知道如何让 scanf() 做这样的事情。我试过寻找字符和循环,但它很纠结。

当我输入 565 856 12 并按 Enter 键时,电话号码只会计算 565。 856 12 用于下一个 scanf。

struct Student{
   unsigned long long student_phone_number;
}


int main(){
   FILE *filePtr;
   filePtr = fopen("std_info.txt","w");

   struct Student Student1;
   printf("\nEnter Student's Phone Number: ");
      scanf("%llu",&Student1.student_phone_number);
      fprintf(filePtr,"%llu\t",Student1.student_phone_number);

}

【问题讨论】:

  • 最好将电话号码视为字符串,而不是整数。前导零不适用于整数。国际前缀(+1、+44 等)不起作用。通常标点符号 - +1 (650)916-2234 - 不起作用。
  • 不要将整数用于电话号码等内容。 Integer 只保存一个数字的值,而不是它的表示。它不区分0123123,也不允许存储+ 等特殊字符。
  • 谢谢,然后将其视为字符。但是,空间是不是很痛苦?
  • @user9560064 是的,scanf 的嵌入空间很麻烦。你有两个选择:(1) 使用相当神秘和有问题的%[…] 格式,或者(2) 根本不使用scanf,改用fgets 之类的东西(尽管那样你必须担心尾随\n)。
  • 请注意,如果您提供问题的minimal reproducible example,问题往往对其他人更有用。由于您的直接问题只是关于从stdin 输入并将其存储在struct 中,而不是关于输出到文件,因此如果您的代码示例仅限于从@987654333 读取,您的问题会更好一些@ 并写信给stdout。相反,通过在问题的发布代码中打开文件以进行输出,您使代码变得比必要的复杂。这可能会降低您的问题获得投票的机会。

标签: arrays c integer numbers


【解决方案1】:

为了解决这个问题,我修改了Student 结构来存储unsigned long long 整数和字符数组。用户从stdin 读取字符数组。读取的数据使用isValid()方法进行验证,字符串使用convertToNumber()方法转换为unsigned long long整数。

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>

struct Student{
    unsigned long long numberForm;  
    char *textForm;             
};

// Converts character array to unsigned long long integer.
void convertToNumber(struct Student * const student);
// Validates the data in the Student.textForm variable.
bool isValid(const char * const input, const char * const format);
// Returns the number of characters in a character array.
size_t getSize(const char * const input);
// This function returns the "base ^ exponent" result.
unsigned long long power(int base, unsigned int exponent);

int main()
{
    struct Student student;
    char format[] = "NNN NNN NN"; /* "123 456 78" */
    
    printf("Enter phone number: ");
    fgets(student.textForm, getSize(format) + 1, stdin); 
    // The gets() function is deprecated in newer versions of the C/C++ standards.
    
    if(isValid(student.textForm, format))
    {
        convertToNumber(&student);
        printf("Result: %llu", student.numberForm);
    }

    return 0;
}

void convertToNumber(struct Student * const student)
{
    int size = getSize(student->textForm) - 2;
    unsigned int temp[size];
    student->numberForm = 0ull;
    
    for(int i = 0, j = 0 ; i < getSize(student->textForm) ; ++i)
        if(isdigit(student->textForm[i]))
            temp[j++] = student->textForm[i] - '0';
    
    for(size_t i = 0 ; i < size ; ++i)
        student->numberForm += temp[i] * power(10, size - i - 1);
}

bool isValid(const char * const input, const char * const format)
{   
    if(getSize(input) == getSize(format))
    {
        size_t i;

        for(i = 0 ; i < getSize(input) ; ++i)
        {
            if(format[i] == 'N')
            {
                if(!isdigit(input[i]))
                    break;
            }
            else if(format[i] == ' ')
            {
                if(input[i] != format[i])
                    break;
            }
        }

        if(i == getSize(input))
            return true;
    }
    return false;
}

unsigned long long power(int base, unsigned int exponent)
{
    unsigned long long result = 1;
    
    for(size_t i = 0 ; i < exponent ; ++i)
        result *= base;
    
    return result;
}

size_t getSize(const char * const input)
{
    size_t size = 0;
    
    while(input[++size] != '\0');
    
    return size;
}

这个程序的工作原理如下:

Enter phone number: 123 465 78
Result: 12346578

【讨论】:

    【解决方案2】:

    您可以使用fgets 来解析带有空格和所有字符的输入:

    #include <stdio.h>
    
    #define SIZE 100
    
    int main() {
        
        char str[SIZE];
    
        fgets(str, sizeof str, stdin); // parses input string with spaces
                                       // and checks destination buffer bounds
                                         
    }
    

    如果你想删除空格,你可以很容易地做到这一点:

    #include <ctype.h>
    
    void remove_white_spaces(char *str)
    {
        int i = 0, j = 0;
        while (str[i])
        {
            if (!isspace(str[i]))
              str[j++] = str[i];
            i++;
        }
        str[j] = '\0';
        
    }
    

    Presto,此函数将从您作为参数传递的字符串中删除空格。

    Live demo

    输入:

    12 4 345 789
    

    输出:

    124345789
    

    之后很容易将其转换为无符号整数值,您可以使用strtoul,但是为什么要将电话号码存储为数字类型,您会对其进行算术运算吗?怀疑。然后你保存到一个文件中,所以它是字符串还是数字类型并不重要。我会把它保存为一个字符串。

    【讨论】:

      【解决方案3】:

      通常最好将电话号码存储为字符串,而不是数字。

      为了将整行输入(不仅仅是一个单词)作为字符串读取,我建议您使用函数fgets

      这是一个基于您问题中的代码的示例:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      struct Student{
         char phone_number[50];
      };
      
      int main( void )
      {
          //open output file (copied from code in OP's question)
          FILE *filePtr;
          filePtr = fopen("std_info.txt","w");
      
          //other variable declarations
          struct Student Student1;
          char *p;
      
          //prompt user for input
          printf( "Enter student's phone number: ");
      
          //attempt to read one line of input
          if ( fgets( Student1.phone_number, sizeof Student1.phone_number, stdin ) == NULL )
          {
              printf( "input error!\n" );
              exit( EXIT_FAILURE );
          }
      
          //attempt to find newline character, in order to verify that
          //the entire line was read in
          p = strchr( Student1.phone_number, '\n' );
          if ( p == NULL )
          {
              printf( "line too long for input!\n" );
              exit( EXIT_FAILURE );
          }
      
          //remove newline character by overwriting it with terminating
          //null character
          *p = '\0';
      
          //write phone number to file
          fprintf( filePtr, "%s\n", Student1.phone_number );
      
          //cleanup
          fclose( filePtr );
      }
      

      【讨论】:

        【解决方案4】:

        为此使用字符串并修剪字符串中的空格,然后使用 atoi 函数将给定的数字转换为整数,要使用 atoi 您必须包含 stdlib.h 头文件。例如

        #include<stdio.h>
        #include<stdlib.h>
        int main(){
                char str[] = "123456";
                unsigned long long int num = atoi(str);
                printf("%llu", num);
        }
        

        【讨论】:

        • atoi() 用于unsigned long long 会带来不快。你可能需要strtoull()
        • 电话号码最好作为特殊字符串处理和存储,而不是数字。
        • 这仍然没有回答我如何使用空格输入的问题,我想将“565 856 12”打印到文件中。但是当编译器看到空间时,它会停止获取变量
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        • 2013-01-18
        • 1970-01-01
        相关资源
        最近更新 更多