简体   繁体   English

如何使用 '%c' 和 scanf() 输入字符串

[英]How can I input a string using '%c' and scanf()

This is the program where I want to input a string with scanf() using '%c' as a format specifier and may use any loop or condition.这是我想用'%c'作为格式说明符输入带有scanf()的字符串的程序,并且可以使用任何循环或条件。

// Online C compiler to run C program online
#include <stdio.h>
#include <stdlib.h>
void clrr(){while (getchar()!='\0');}
int main() {
    // Write C code here
    char str[5];
    int i=0;
    char a;
    while (i<5){
        scanf("%1c",str[i]);
        a=getchar();
        if (a=='\n') {
                break;
            };
        i++;
        str[i]=a;
        i++;
        //clrr();
    }
    //str[i+1]='\0';
   printf("\n%s",str);
    return 0;
}

try this...尝试这个...

#include <stdio.h>
#include <stdlib.h>
void clrr(){while (getchar()!='\0');}
int main() {
// Write C code here
    char str[5];
    int i;
    for(i=0;i<5;i++){
        scanf(" %c",&str[i]);
    }
    for(i=0;i<5;i++){
       printf("%c",str[i]);
    }
    return 0;
}
// Online C compiler to run C program online
#include <stdio.h>
int main() {
    // Write C code here
    char str[5];
    int i=0;
    for(i=0;(i<5)&&((i>0)?(str[i-1]!='\n'):(1));i++){
        scanf("%1c",&str[i]);
    }
    str[i-1]='\0';
    printf("\n%s",str);
    return 0;
}

I guess this is the solution... by InZamam我想这就是解决方案……作者:InZamam

'''// Online C compiler to run C program online
#include <stdio.h>
int main() {
    // Write C code here
    char str[5];
    int i=0;
    for(i=0;(i<5)&&((i>0)?(str[i-1]!='\n'):(1));i++){
        scanf("%1c",&str[i]);
    }
    str[(str[i-1]!='\n')?(i):(i-1)]='\0';
    printf("\n%s",str);
    printf("..");
    return 0;
}
'''

A little modified due to preservation of data:由于保存数据,稍作修改:

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

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