简体   繁体   中英

Program in C++ doesn't stop on if(scanf()==EOF)break;

My program in C++ doesn't stop on if(scanf()==EOF)break; , below is sketch of my program, for example input:

X XjhgXjhX

gives output:

jhgjh

that is - it prints all characters except X , but it doesn't stop on Ctrl+Z .

using namespace std;

int main()
{
    char str[100]={0},znak,forbd;
    int i=0,j=0;
    while(true)
    {
        i=0;
        j=0;

        if(scanf("%c",&forbd)==EOF)
            break;

        if(scanf("%c",&znak)==EOF)
            break;

        while(znak!='\n')
        {
            if(forbd!=znak && znak!=' ')
            {
                str[i]=znak;
                i++;
                //cout<<i<<"\n";
            }

            if(scanf("%c",&znak)==EOF)
                break;
        }

        while(j<i)
        {
            printf("%c",str[j]);
            j++;
        }
        printf("%c",'\n');
    }
    return 0;   
}

I don't want to use cin , because of trouble with reading \\n .

ok, I'm going to use iostream instead of cstdio with code if(cin.peek()=='\\n')break; detecting end of line, this solves issue.

scanf reads from stdin reference witch:

stdin is known to not refer to an interactive device, the stream is fully buffered. Otherwise, it is library-dependent whether the stream is line buffered or not buffered by default (see setvbuf).

Usually, stdin is line buffered and you need to type '\\n' to read.

From an correlated question you can find solutions for this type use case of character reading.

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