Find the answer to your Linux question:
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]; ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just 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:
    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;
    }
    but its reding string a as null string at time i read n and hit a enter.

  2. #2
    Linux Guru coopstah13's Avatar
    Join Date
    Nov 2007
    Location
    NH, USA
    Posts
    3,149
    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

  3. #3
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    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:
    Code:
    if(*a == '\0')
        printf("null string\n");
    This is because if a is not an empty string, this doesn't require traversing it to find out its length.

  4. #4
    Just Joined! ultimatelinux's Avatar
    Join Date
    Mar 2010
    Posts
    36
    equivalent of a white space is '\0'
    a new line '\n'
    a tab '\t'

  5. #5
    Linux Guru Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,252
    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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •