简体   繁体   English

将特定字符扫描到C中的数组中

[英]Scanf specific Characters into array in C

I am currently taking a basic C course and I was wondering why my code below doesn't run. 我目前正在学习基本的C课程,并且想知道为什么下面的代码无法运行。

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

int main()
{ 
    char string[4];

    printf("Enter some text\n");
    scanf(" %c %c %c", &string[0], &string[1], &string[2]);

    printf("You Entered ");

    int i;
    for (i = 0; i < 4; i++){
        printf("%c",string[i]);
    }

    return 0;
}

Xcode said there is an errr with my scanf line. Xcode说我的scanf行有一个错误。

I was hoping to type in "abcd" and expect a "You entered abcd"; 我希望输入“ abcd”并期望输入“您输入了abcd”。

This code should run (albeit with a bug). 此代码应运行(尽管有错误)。 I suspect you need to configure the Xcode build options correctly. 我怀疑您需要正确配置Xcode构建选项。

As for the bug, you have an array of four chars, but you are only scanning for three. 至于错误,您有四个字符的数组,但是您只扫描了三个。 Add another %c and &string[3] to your scanf line. 在您的scanf行中添加另一个%c&string[3]

Here's an ideone snippet showing the modified code in action 这是一个ideone片段,显示了修改后的代码

#include <stdio.h>

int main()
{ 
    char string[4];
    int i;

    printf("Enter some text\n");
    scanf("%c %c %c %c", &string[0], &string[1], &string[2], &string[3]);

    printf("You Entered ");

    for (i = 0; i < 4; i++){
        printf("%c", string[i]);
    }

    return 0;
}

This compiles just fine on the Mac command line (assuming the source is in "test.c") 这在Mac命令行上可以正常编译(假设源位于“ test.c”中)

$ cc -g -Wall -o test test.c 
./test
Enter some text
a b c d
You Entered abcd

Also note that this particular snippet requires only stdio.h ( man scanf and man printf will tell you which header to use). 另请注意,此特定代码段仅需要stdio.hman scanfman printf会告诉您要使用哪个标头)。

How about executing this code? 如何执行此代码?

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

int main()
{ 
    char strin[10];

    printf("Enter some text\n");
    scanf("%s", strin);

    printf("You Entered %s",strin);

    return 0;
}

The following code gives you : 以下代码为您提供:

Enter some text
abcd
You Entered abcd

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM