I have input where we get to know that the current testcase has finished and next started by a blank line in between. How can I check that if a blank line has occurred in C++?
Asked
Active
Viewed 628 times
0
-
3How are you reading the input? – Weak to Enuma Elish Feb 24 '16 at 05:41
-
1By reading a line, and testing if it is a blank line... What issue are you having? How to read a line? How to test if it is blank? What have you tried? – hyde Feb 24 '16 at 05:53
2 Answers
3
There're many ways to detect a blank line (if the line doesn't contain spaces, of course).
Example 1 (it's supposed you're getting your data line by line):
#include <string.h>
...
if (strcmp(yourLine, "") == 0) { // or strcmp(yourLine, "\n"), it depends how you get yourLine in your code above
// your code
...
}
Example 2:
#include <string>
std::string yourData = "qwe\nrty\n\nasd\nfgh\n";
std::size_t index;
while ((index = yourData.find("\n\n")) != std::string::npos) {
std::string part = yourData.substr(0, index);
// your code
yourData = yourData.substr(index);
}
In Example 2 methogs std::string::find and std::string::substr were used. You can look at the documentation for them: http://www.cplusplus.com/reference/string/string/find/, http://www.cplusplus.com/reference/string/string/substr/

Fomalhaut
- 8,590
- 8
- 51
- 95
-
1
-
It only works if you have valid NUL-terminated C string... And you really don't want to go there unless you have to interface with some C library or some such. Basically, it is an advanced and obscure topic from C++ point of view (and a major source of bugs in C). – hyde Feb 24 '16 at 06:02
-
if (strcmp(yourLine, "") == 0) will check if there is a new line ? – Vatsal Sharma Feb 24 '16 at 06:43
-
-
Then I'd recommend you to use (s.compare("") == 0), because the type of s is std::string. Or (strcmp(s.c_str(), "") == 0). Or (s.empty()). There're many ways to check, if you use getline, because this routine cuts '\n' symbol out. – Fomalhaut Feb 24 '16 at 07:02
1
You will need to check for '\r', '\n', or "\r\n" depending on what OS your code is running on. See Difference between \n and \r? for a good explanation on why this is OS-dependent.

Community
- 1
- 1

StoneThrow
- 5,314
- 4
- 44
- 86