简体   繁体   中英

Taking string as input character by charcter and giving output on pressing enter

I want to write a program in C or C++ which takes a string as a input character by character and gives output when enter key is pressed. I have to take the input character by character .

    while (1)
    {
            scanf("%c",&a); //cin>>a;
            if(a=='\n')
            break;
            //do operation on the character
    }
    //give output

something like this but I am not able to do it.

IIUC, you're looking for the getchar function:

while (1)
{
        char c = (char)getchar();
        if(c=='\n')
        break;
        //do operation on the character
}
//give output

Ideally your code should work properly. Since a scanf reads a character and stores it. What is the error/output you are getting?

Also try comparing (a==10) 10 is the ascii value of '\\n'

Try this:

int main()
{
    char str[100],c;
    int i =0;
    while((c=getc(stdin)) != '\n')
    {
        str[i] = c;
        i++;
    }
    str[i] = '\0';
    printf("%s",str);
    return 0;
}

Here is one way:

char ch;
while(1)
{
    if((ch=getchar())=='\n')
        break;
}// its working fine

And another way:

char ch;
while(1)
{
    scanf("%c",&ch);
    if((ch=='\n'))
        break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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