Reading Numbers as Strings

How to read numbers from a mixed txt file in python

If you know how to use python regex module you can do that:

import re

if __name__ == '__main__':

with open(TEST_FILE, 'r') as file_1:
for line in file_1.readlines():

if re.match(r'(\d+\s){4}', line):
line = line.strip() # remove \n character
print(line) # just lines with four numbers are printed

The result for you file example is:

567 45 32 468
974 35 3578 4467
325 765 355 5466

Reading A Variable As Both A Number And String of Words

This is impossible. Pascal is a strictly typed language, and something cannot be an Integer and a string at the same time, and variables cannot change type either:

 IF Dep_Code = 1 THEN
Dep_Code := ('Accounts (ACC)')

But you don't need a string at all. Keep it an integer. The functions that handle the various depts can write or define such strings, if necessary. Your logic for the menu does not need a string variable.

Do something like:

procedure HandleAccounts(var Error: Boolean);
begin
...
end;

// Skipped the other functions to keep this answer short ...

var
Dep_Code: Integer;
AllFine: Boolean;

// Skip the rest of the necessary code ...

repeat

// Skipped the Writelns to keep this answer short ...

Readln(Dep_Code);
Error := False;

case Dep_Code of
1: HandleAccounts(Error);
2: HandleHumanResources(Error);
3: HandleOperations(Error);
else
Error := True;
end;

until not Error;

Above, I skipped some of the code. You can fill in the blanks, I guess.

reading string with spaces and then integers from same line in file

I highly suggest in the future to learn how to debug your code. To be honest, I did not found the solution right at the top so I copied the code, and ran in on my machine and I got the wrong output, like you. Then, I debugged my code and I noticed the string is read correctly, and the numbers remain untouched. To make sure, I created a variable to hold the return value from scanf, and indeed it was 1 since only the string was getting the input.

I then first tied to add a space between %[^:] and %d, but to no avail. Then I looked at the file again, and the string I got on aa variable and noticed the : was in the file, but not in aa. Where did it go? nowhere, it was still in the buffer waiting to be read. In order to "skip" it, you could just add : sign after %[^:], so the command would "eat it", and after doing it on my machine it worked.

The short answer, is to change the scanf line to:

fscanf(fp, "%[^:]:%d %d %d", aa, &a, &b, &c);

The long answer, is to learn how to debug you code correctly, It took my less than 2 minutes to figure it out and I'm sure that if you tried yourself, you could find the solution too.

Of course if you try debugging yourself with no avail, you are always welcome to open a topic!



Related Topics



Leave a reply



Submit