• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: not terminating scanf() or gets() after taking newline

Resolved: not terminating scanf() or gets() after taking newline

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have to take three inputs in a single string.
The code to take the input is:
The input is like

That means there is a newline after the fist line GET /api HTTP/1.1. The next line is an empty newline. The input taking function should terminate after taking the 3rd newline.
Also, I have to terminate the input after the first line GET /something HTTP/1.1 if the line doesn’t have a /api word at the place of /something word.
But when I’m using gets(), it terminates the string after taking GET /api HTTP/1.1 part of the input. When using scanf, it terminates after taking only the first GET word. Is there any way to take the input as a single string?

Answer:

In cases like these, you should just use getchar in a loop:

#define MAX_MSG_BUF 1000

char char msg_send[MAX_MSG_BUF];

// you should wrap the below code in a function, like get3lines(buf, buf_size)
unsigned index = 0;
unsigned line_count = 0;
const unsigned buf_size = MAX_MSG_LEN;
do {
int tmp = getchar();
if (tmp < 0) break; // end of file or error msg_send[index++] = tmp; if (tmp == '\n') { ++line_count; if (line_count == 1) { // check that first line contains /api if (!strnstr(msg_send, "/api", index) break; } } } while (index < (MAX_MSG_BUF-1) && line_count < 3; msg_send[index] = '\0'; // print error if line_count < 3 ? [/code]

If you have better answer, please add a comment about this, thank you!

Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to efficient create SimpleITK image?

01/04/2023

Resolved: How can I write CSS selector(s) that apply to table rows for all td elements on that row after a td with a certain class?

01/04/2023

Resolved: How do I use SetWindowText with Unicode in Win32 using PowerShell?

01/04/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.