【问题标题】:Program isn't printing first digits of two strings程序不打印两个字符串的第一位数字
【发布时间】:2022-11-21 14:31:06
【问题描述】:

嗨,我正在通过《现代方法》一书学习 C。对于这个程序,我们只需要输入名字和姓氏,程序应该返回 Last Name, First Initial。

char *first [255];
 char *last [255];
 printf("Enter a first name and a last name: ");
 while (getchar() == ' ');
 scanf("%s", first);
 while (getchar() == ' ');
scanf("%s", last);
 while (getchar() == ' ');

 char firstInitial = (char) first[0];
 printf("%s, ", last);
 putchar(firstInitial);

当我运行它时,它不打印前两个字符。

例如 输入名字和姓氏:Aaron Smith 史密斯

【问题讨论】:

    标签: char user-input


    【解决方案1】:

    这将使您开始获得名字。

    #include <stdio.h>
    
    int main() {
      // Create a string
      char firstName[255];
    
      // Ask the user to input some text
      printf("Enter your first name: 
    ");
    
      // Get and save the text
      scanf("%s", firstName);
    
      // Output the text
      printf("first name %s.  1st char %c", firstName, firstName[0]);
      
      return 0;
    }
    

    【讨论】:

      【解决方案2】:
      #include <stdio.h> 
      void main() 
      { 
       char a = getchar(); 
       char b; 
       scanf("%c",&b); 
       printf("%c",b); 
      } 
      

      运行上面的代码并亲自查看结果。

      您可以看到 getchar() 函数仅在按下“enter”键后才终止。

      这会导致额外的‘ ’ 字符连同您输入的单个字符一起出现在输入队列中。

      所以字符'b'被分配' ’并且编译器不会提示您为‘b’提供输入。

      【讨论】:

        猜你喜欢
        • 2017-06-25
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2013-02-08
        • 2021-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多