【问题标题】:How do you include spaces in a scanf string?如何在 scanf 字符串中包含空格?
【发布时间】:2017-09-11 06:57:59
【问题描述】:

只要“主要”变量只有一个词,这个程序就可以工作。例如,CIS 是一个有效的输入,但计算机信息系统不是。我该如何解决这个问题?

#include<stdio.h>

int main()
{
char major [51];
int classes;

printf("What is your major? ");
scanf("%50s", major);

printf("How many classes are you taking this semester? ");
scanf("%d", &classes);

printf("Your major is %s and you are taking %d classes this semester.\n", major, classes);
}

【问题讨论】:

标签: c char scanf


【解决方案1】:

您的问题是 scanf 在第一个空格处停止。你需要做的是继续阅读,直到你读到结束行字符。

使用 scanf 可以做到这一点,但有更好的选择。 fgets() 立即浮现在脑海中。 https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

在 Stack Overflow 上进行一些搜索会产生大量关于 scanf()fgets() 与其他主题的主题。 Using fscanf() vs. fgets() and sscanf()

【讨论】:

    【解决方案2】:

    您可以使用%50[^\n] 匹配最多50 个字符,直到遇到换行符,并将它们存储在major[] 中。换行符将留在输入流中,但 %d 转换说明符会自动跳过前导空白字符。

    请注意,如果用户输入的字符超过 50 个,在调用scanf() 获取类数之前,输入流中会有多余的字符需要丢弃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-05
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多