0

I have a text file that looks like the following:

12345678909876543211234567890
09876543122345678900

I will eventually need to add these two values together using separate stacks so I want to push each digit into a stack separately so I have code like the following:

test=fopen("test.txt","r");
while (!feof(fp)) {
    fscanf(test, "%1d", &number);
    Push((Item)number, &num1);
}

I need to modify my code though so that it reads the first line 1 digit at a time, pushing on each digit, and then for the next line I need it to push into another stack called num2 instead of num1 as you see in the current code.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ComputerLocus
  • 3,448
  • 10
  • 47
  • 96
  • @user3121023 wouldn't that scan them in as a char though? – ComputerLocus Oct 13 '15 at 23:43
  • 1
    Read a line of data; push the digits onto the stack. Read the next line; push the digits onto the other stack. Use the Standard C function [`fgets()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html) or the POSIX function [`getline()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html) to read the lines. – Jonathan Leffler Oct 13 '15 at 23:45
  • See also [Why is `while (!feof(file))` always wrong?](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Jonathan Leffler Oct 13 '15 at 23:49
  • @user3121023 your method worked properly and I now have it working using that. Feel free to submit an answer and I can accept that. – ComputerLocus Oct 13 '15 at 23:51

1 Answers1

3

You've not told us about the stack types, so I'm inventing one — typedef name is Stack:

Stack num1, num2;
Stack *stacks[2] = { &num1, &num2 };

…initialize stacks
…open file and check that the open was successful

for (int i = 0; i < 2; i++)
{
    char line[4096];
    if (fgets(line, sizeof(line), test) == 0)
        …report unexpected EOF or other error; do not continue…
    char *digit = line;
    while (isdigit((unsigned char)*digit))
        Push((Item)(*digit++ - '0'), stacks[i]);
    if (*digit != '\n' && *digit != '\0')
        …report unexpected (non-digit) data on input; do not continue;
}

I assume that Push is a function, not a macro that might evaluate its first argument more than once. If it is such a macro, the loop body needs be split onto two lines and braces added so that the increment of digit is separate from the function call.

Note that one major advantage of this method is that you have the whole line of data available for error reporting, which is typically easier for people to understand than only being able to report on the dribs and drabs left over after a semi-indeterminate number of characters was read from the line by a scanf() loop. You can even use sscanf() on the line if you want to — see How to use sscanf() in loops?

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278