c - scanf 函数内的空白 - C 编程

标签 c

从之前的帖子中,我知道您可以使用此处所示的方法来实现此目的:How do you allow spaces to be entered using scanf?

它在 Main 中工作,但是当我将它放入函数中时,它不起作用。

这是我的代码:

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

void dataInput();
struct record {
    char title[50];
    char author[50];
    char category[20];
    float price;
}; 

struct record info[500];

void main(){
    dataInput();
}

void dataInput(){
    int x;
    for(x = 0; x <= 10; x++ ){
        scanf("%s", &info[x].title);
        printf("%s\n", &info[x].title);
    }
}

输出:

Output1

如果我使用正则表达式:

scanf("%50[0-9a-zA-Z ]s", &info[x].title);

输出:

Output2

嗯,这里出了什么问题

最佳答案

我还没有手写最可靠的引用手册,但是来自 Wikipedia :

%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.

因此,%sscanfprintf 中执行非常不同的操作,并且实际上只读取一个scanf 中的单词,而在 printf 中它将产生指向的空终止内容。

关于c - scanf 函数内的空白 - C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23989680/

相关文章:

c - 为什么我会在这里得到这个意外的输出? "87"

c - 是否可以通过 mmap 匿名内存访问 "punch holes"?

c++ - getaddrinfo 内存泄漏

c++ - 将迭代函数转换为递归

c - 如何使用我的字符串将 "interleave"C/C++ 源代码(仅在适当位置的内部函数中)?

c - 整数和数组之间的奇怪转换

c - PTHREAD_MUTEX_INITIALIZER 与 pthread_mutex_init ( &mutex, param)

c - pthread 的变量变化

c - 给定一个变量,尝试打印位的每个组合

c - 编写 numpy ufunc 时如何处理复数值?