How can I read numbers from an external text file in C?

0
12
Asked By CuriousCoder93 On

I'm trying to read a number between 1 and 6 from an input.txt file in C, but my program keeps getting stuck on the first number it encounters. I've tried debugging this without success. If anyone has insights or solutions that could help me, I'd really appreciate it! I'm using a scanf call to get the input like this: scanf("%d", &choose); and I'm checking that the number is between 1 and 6 with a while loop.

3 Answers

Answered By DebugMaster On

Make sure to check the result of your scanf function to see if it's reading the input correctly. You can add error handling for cases where the input is not what you expect. Here’s an example code snippet:

```c
#include
int main() {
for (int n, result;;) {
result = scanf("%d", &n);
if (result == 1) {
if (n >= 1 && n <= 6) {
printf("Valid: %dn", n);
} else {
printf("Out of bounds: %dn", n);
}
} else {
if (result = 0 && c != 'n';);
}
}
}
```
This helps to ensure that your program can handle wrong inputs without getting stuck! You can check it out on platforms like godbolt.org for testing.

Answered By TechSavvy21 On

First off, how is your program set up to read from the input.txt file? Just checking because it’s important for it to know where to retrieve the data from! You might want to use a command like `gcc ex.c -o program.exe` followed by `Get-Content input.txt | ./program.exe` to run it properly and see if that helps. Let me know what you think!

Answered By FileReaderExpert On

Can you share what the content of your input.txt file looks like? It might help diagnose the issue if we can see the actual data your program is trying to read.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.