0

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++?

drescherjm
  • 10,365
  • 5
  • 44
  • 64

2 Answers2

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
    Why even consider strcmp in C++? – hyde Feb 24 '16 at 05:55
  • 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
  • I get the input by getline(cin,s) – Vatsal Sharma Feb 24 '16 at 06:48
  • 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