Ashfaqur_Rahman
Ashfaqur_Rahman

Reputation: 158

Input is ended with an end-of-file character (EOF) in C, C++ and Python

I start learning Python language a few days ago. My skill in python is not too much high. But whatever I learn, I want to solve UVA Online Judge problem

When I try to solve the problem 272 TEX Quotes I faces a problem to terminate loop when user input is given by end-of-file.

Check my (100% logic solved) code in python (except while loop terminate)

flag = True;

while True: #I want That loop is terminated when getting EOF
    txt = input()

    for var in txt:
        if var == '"':
            if flag:
                print("``", end='')
            else:
                print("''", end='')
            flag = not flag
        else:
            print(var, end='')

    print(end='\n')

Check my accepted solved code in C it's terminate loop with end-of-file which is given by Ctrl + Z

#include <stdio.h>

int main()
{
    int flag = 1;
    char txt;

    while((txt = getchar()) != EOF){
        if(txt == '"'){
            if(flag)
                printf("``");
            else
                printf("''");

            flag = !flag;
        }else
            putchar(txt);
    }
    return 0;
}

Also, C++

#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
    char txt;
    bool flag = true;

    while((txt = getchar()) != EOF){
        if(txt == '"'){
            if(flag)
                cout << "``";
            else
                cout << "''";

            flag = !flag;
        }else
            cout << txt;
    }
    return 0;
}

Upvotes: 1

Views: 4965

Answers (1)

Amaro Vita
Amaro Vita

Reputation: 436

EOF while input raises EOFError so you can use try … except block with break statement:

flag = True;

while True: #I want That loop is terminated when getting EOF
    try:
        txt = input()

        for var in txt:
            if var == '"':
                if flag:
                    print("``", end='')
                else:
                    print("''", end='')
                flag = not flag
            else:
                print(var, end='')

        print(end='\n')
    except EOFError:
        break

Upvotes: 2

Related Questions