7

I'm trying to solve a Krypto Problem on https://www.spoj.pl in Python, which involves console input.

My Problem is, that the Input String has multiple Lines but is needed as one single String in the Programm. If I just use raw_input() and paste (for testing) the text in the console, Python threats it like I pressed enter after every Line -> I need to call raw_input() multiple times in a loop.

The Problem is, that I cannot modify the Input String in any way, it doesn't have any Symbol thats marks the End and I don't know how many Lines there are.

So what do I do?

Dreiven
  • 687
  • 3
  • 9
  • 22

4 Answers4

7

Upon reaching end of stream on input, raw_input will return an empty string. So if you really need to accumulate entire input (which you probably should be avoiding given SPOJ constraints), then do:

buffer = ''
while True:
    line = raw_input()
    if not line: break

    buffer += line

# process input
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • 1
    I tried this, but unfortunately this doesn't seem to work. If I press Enter after pasting the Text, the programm still waits for more Input -> I need to press Enter in the new and empty Line. SPOJ seems to have similar behaviour. – Dreiven May 01 '11 at 19:10
  • @Dreiven: Strip the whitespace (`raw_input().strip()`). – Cat Plus Plus May 01 '11 at 19:11
  • @Dreiven: You can try `sys.stdin.read()`, but it's likely that both this and above code will exhaust available memory. – Cat Plus Plus May 01 '11 at 19:24
1

Since raw_input() is designed to read a single line, you may have trouble this way. A simple solution would be to put the input string in a text file and parse from there.

Assuming you have input.txt you can take values as

f = open(r'input.txt','rU')
for line in f:
  print line,
Antony Thomas
  • 3,576
  • 2
  • 34
  • 40
1

Using the best answer here, you will still have an EOF error that should be handled. So, I just added exception handling here

buffer = ''
while True:
    try:
         line = raw_input()
    except EOFError:
         break
    if not line: 
         break

    buffer += line
Chris Travers
  • 25,424
  • 6
  • 65
  • 182
sulabh chaturvedi
  • 3,608
  • 3
  • 13
  • 25
1

Since the end-of-line on Windows is marked as '\r\n' or '\n' on Unix system it is straight forward to replace those strings using

your_input.replace('\r\n', '')

  • I can't replace it like this because raw_input() is called for every Line seperately. – Dreiven May 01 '11 at 19:18
  • Then you have to collect your data into a buffer or a list....this is straight forward.. –  May 01 '11 at 19:19
  • I have to call raw_input() multiple times, once for each Line of my Input -> I don't know how many Lines there are -> I try PiotrLegnicas Solution -> The Loop won't terminate. Removing the breaks is really no Problem after I gathered all the Input. – Dreiven May 01 '11 at 19:25