使用 scanf 读取字符串作为输入 [英] Read a string as an input using scanf

查看:35
本文介绍了使用 scanf 读取字符串作为输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 语言的新手,我正在尝试从用户那里读取一个字符和一个字符串(一个句子;最大长度为 25).

I am new to C language and I am trying read a character and a string (a sentence; max-length 25) from a user.

不确定我在以下代码行中做错了什么,它给了我一个错误段错误".

Not sure what I am doing wrong in the following lines of code, its giving me an error "Segment Fault".

#include <stdio.h>

int main(){
    char * str[25];
    char car;

    printf("Enter a character: ");
    car = getchar();

    printf("Enter a sentence: ");
    scanf("%[^\n]s", &str);

    printf("\nThe sentence is %s, and the character is %s\n", str, car);

    return 0;
}

谢谢!

推荐答案

str 是指向 char 的 25 个指针的数组,而不是 char<的数组/代码>.所以把它的声明改成

str is an array of 25 pointers to char, not an array of char. So change its declaration to

char str[25];

并且您不能使用 scanf 来阅读句子——它会在第一个空格处停止阅读,因此请改用 fgets 来阅读句子.

And you cannot use scanf to read sentences--it stops reading at the first whitespace, so use fgets to read the sentence instead.

并且在您的最后一个 printf 中,您需要 %c 说明符来打印字符,而不是 %s.您还需要刷新标准输入,因为在stdin 中还有一个'\n',因此您需要将这些字符扔掉.

And in your last printf, you need the %c specifier to print characters, not %s. You also need to flush the standard input, because there is a '\n' remaining in stdin, so you need to throw those characters out.

修改后的程序现在是

#include <stdio.h>    
void flush();
int main()
{
    char str[25], car;

    printf("Enter a character\n");
    car = getchar();

    flush();

    printf("Enter a sentence\n");
    fgets(str, 25, stdin);

    printf("\nThe sentence is %s, and the character is %c\n", str, car);

    return 0;
}
void flush()
{
    int c;
    while ((c = getchar()) != '\n' && c != EOF)
        ;
}

这篇关于使用 scanf 读取字符串作为输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆