Results 1 to 5 of 5
in gcc how to read a blank line ie a string of length 0.
my code:
Code:
#include<stdio.h>
#include<string.h>
#include<string>
using namespace std;
int main()
{ int n;
char a[151];
...
- 04-20-2010 #1Just Joined!
- Join Date
- Jan 2010
- Posts
- 4
in gcc how to read the presence of a blank line
in gcc how to read a blank line ie a string of length 0.
my code:but its reding string a as null string at time i read n and hit a enter.Code:#include<stdio.h> #include<string.h> #include<string> using namespace std; int main() { int n; char a[151]; scanf("%d",&n); while(n--) { gets(a); if(strlen(a)==0)printf("null string\n"); } return 0; }
- 04-20-2010 #2
you are writing c++ code based on your use of namespaces no?
why do you include string 2 times, only include it once, you don't need .h since you are using namespace std
you should use cin and getline in c++ imo
- 04-20-2010 #3
If you're using C++, as coopstah says, you should use cin instead of gets(). Even if you're using C, gets() is a very dangerous function: you should use fgets() instead (it allows you to give a string length, which avoids buffer overflow attacks).
Anyway, I think that your problem is related to scanf(). If your input to the first prompt (for n) is "4\n" (that is, "4" followed by enter), the 4 gets put into n, but the newline is left in the stream. Therefore, gets() sets a to a blank string, because the next character is a newline.
You need to change your scanf() to:
Code:scanf("%d\n", &n);
As a side note, a more efficient way to check for an empty string is:
This is because if a is not an empty string, this doesn't require traversing it to find out its length.Code:if(*a == '\0') printf("null string\n");DISTRO=Arch
Registered Linux User #388732
- 04-20-2010 #4
equivalent of a white space is '\0'
a new line '\n'
a tab '\t'
- 04-20-2010 #5
That is not quite correct. \0 indicates the end of a string: it is a null byte. Whitespace is indicated by the equivalent character: ' ' for a space, \n for a newline, or \t for a tab.
DISTRO=Arch
Registered Linux User #388732


Reply With Quote