The best example of scanf for strings i can make. #196639
Replies: 3 comments 2 replies
-
|
💬 Your Product Feedback Has Been Submitted 🎉 Thank you for taking the time to share your insights with us! Your feedback is invaluable as we build a better GitHub experience for all our users. Here's what you can expect moving forward ⏩
Where to look to see what's shipping 👀
What you can do in the meantime 💻
As a member of the GitHub community, your participation is essential. While we can't promise that every suggestion will be implemented, we want to emphasize that your feedback is instrumental in guiding our decisions and priorities. Thank you once again for your contribution to making GitHub even better! We're grateful for your ongoing support and collaboration in shaping the future of our platform. ⭐ |
Beta Was this translation helpful? Give feedback.
-
|
Nice attempt! A few thoughts: Your That said, most experienced C devs avoid char text[50];
while (1) {
if (!fgets(text, sizeof(text), stdin)) {
clearerr(stdin);
printf("\nEnter valid text only.\n\n");
continue;
}
text[strcspn(text, "\n")] = '\0';
if (text[0] == '\0') {
printf("\nEnter valid text only.\n\n");
continue;
}
break;
}Key advantages over
Your |
Beta Was this translation helpful? Give feedback.
-
|
Using That said, here's the reality check: even with this pattern, The core problem with scanf for strings
The simpler alternativeInstead, consider using if (fgets(text, sizeof(text), stdin) != NULL) {
text[strcspn(text, "\n")] = '\0'; // Remove newline
// Process text
} else {
// Handle EOF or error
}Why this is cleaner:
Your approach is still solid for learning!If this is for a learning project and you want to master Keep pushing on input validation though—that's a real skill |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
🏷️ Discussion Type
Product Feedback
Body
In all my projects i never use scanf for user input. I do sometimes try to make it work.
The example below works the best i came up with. It does white spaces and sends a error message when the user presses ctrl + d and sends the error message when the user just presses enter. I am sure there are better ways.
/Enter a selection from choices x to exit ch for choices.
//scb
//Enter the name of variable m for main.
//text
//Enter memory allocated to variable 2 or more.
//50
//Enter the name of the function to flush input buffer.
//flush
//Enter a error message. Enter valid text only will do.
//Enter valid text only.
while(scanf("%49[^\n]",text)!=1) {
flush();
printf("\nEnter valid text only.\n\n");
clearerr(stdin);
}
while(1) {
if(scanf("%49[^\n]",text)!=1) {
flush();
printf("\nEnter valid text only.\n\n");
clearerr(stdin);
continue;
}
//Enter a selection from choices x to exit ch for choices.
Guidelines
Beta Was this translation helpful? Give feedback.
All reactions