Hi All,

I am facing the scanf() function problem, below given is a small code snippet where am facing the problem.

int main()
{
     char str1[100];
     char str2[100];

    printf("Enter 1st string\n");
    scanf("%[^\n]s",&str1);

    printf("Enter 2nd string\n");
    scanf("%[^\n]s",&str2);
  
   printf("1st string is %s\n", str1);
   printf("2nd string is %s\n", str2);
 
  return 0;
}

The first string is taking the input properly along with white spaces. But the second string is not at all taking anything. It is showing blank, when i print the second string. I am not understanding how to solve this problem, please help me out from this. I suspect it will be something regarding the use of fflush to clear to user input given for first string.

Thanks in advance

Regards,
Raghavendra. H. R

Edited 7 Years Ago by Nick Evan: Added code-tags

Points to be noted, raghuhr84

  • Give the complete program, that is, give #include<stdio.h> . Becomes easier for us to check.
  • Use proper indentation
  • Use code tags around your program (See the forum rules)

The problem is that you have not flushed stdin. Put fflush(stdin); before the scanf . That should do it.
Here is the complete program :-

#include <stdio.h>

int main()
{
	char str1[100];
	char str2[100];

	printf("Enter 1st string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str1);

	printf("Enter 2nd string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str2);

	printf("1st string is %s\n", str1);
	printf("2nd string is %s\n", str2);

	return 0;
}

Edited 7 Years Ago by xavier666: n/a

Comments
Well said
Read the manual and be clear beforr you post. fflush is not meant to flush stdin it for stdout.
flushing an input buffer is meaningless, and adatapost should know better.
fflush(stdin) invokes undefined behaviour
Well said.

Dear xavier666,

First of all sorry for sending unorganised code, am new to this website. I made the changes whatever u have mentioned. But its of no use, its not working like that also. I am working in Fedora core 6 OS, will it make any diff.

First of all sorry for sending unorganised code, am new to this website

Mistakes happen, no big deal.

I am working in Fedora core 6 OS

Maybe that's the problem because I'm using XP. It's working perfectly fine in my computer.
Try using gets(str1); and gets(str2); in place of scanf() What compiler are you using?

I tried this in Mandriva and it worked

#include <stdio.h>

int main()
{
	char str1[100];
	char str2[100];

	printf("Enter 1st string\n");
	scanf("%[^\n]s",&str1);
	fgetc(stdin);

	printf("Enter 2nd string\n");
	scanf("%[^\n]s",&str2);

	printf("1st string is %s\n", str1);
	printf("2nd string is %s\n", str2);

	return 0;
}

Edited 7 Years Ago by gerard4143: n/a

Points to be noted, raghuhr84

  • Give the complete program, that is, give #include<stdio.h> . Becomes easier for us to check.
  • Use proper indentation
  • Use code tags around your program (See the forum rules)

The problem is that you have not flushed stdin. Put fflush(stdin); before the scanf . That should do it.
Here is the complete program :-

#include <stdio.h>

int main()
{
	char str1[100];
	char str2[100];

	printf("Enter 1st string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str1);

	printf("Enter 2nd string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str2);

	printf("1st string is %s\n", str1);
	printf("2nd string is %s\n", str2);

	return 0;
}

It is understandable that most code posted in this forum are amateurish, but promoting the use of undefined behavior by the use of fflush(stdin) wins the contest. fflush() should be used only with stream output. scanf() is best to leave behind when obtaining string is concerned. Unless you want to learn all the possible ways in which it doesn't work. fgets() is a more ruling function for it.

Edited 7 Years Ago by Aia: n/a

>scanf("%[^\n]s",&str1);
Scansets are a specifier on their own, not a part of the %s specifier. This format string reads up to a newline, then tries to match the character 's'. In your specific case it's not going to cause a problem, but if you try to convert anything after that, you'll get unexpected results.

>The problem is that you have not flushed stdin. Put
>fflush(stdin); before the scanf . That should do it.

Yes, that should do it. "It" being break the program by invoking undefined behavior. :icon_rolleyes: Please don't recommend poor practices.

>Try using gets(str1); and gets(str2); in place of scanf()
Seriously dude, you should learn a little more about C before trying to help people. You're pushing the worst possible options. Have you never learned that gets is 100% unsafe and impossible to make safe?

Dear raghuhr84,

please disregard everything Xavier666 has said. anyone who suggests flushing the input buffer or using gets() has no business instructing anyone in the C language. (I'm also concerned as to why a moderator on this site (adatapost) would endorse his "solution" by giving him a green dot, but that's another issue.)

regarding your problem, I would recommend that for basic input, you use the "fgets()" function. "fgets" will get the input then you will parse it afterwards. "scanf()" has a lot of powerful functionality, but is susceptible to user error and can cause a lot of grief.

int main(void)
{
    char str1[100];
    char str2[100];

    printf("Enter 1st string\n");
    fgets(str1, 100, stdin);

    printf("Enter 2nd string\n");
    fgets(str2, 100, stdin);
  
    printf("1st string is %s\n", str1);
    printf("2nd string is %s\n", str2);
 
    return 0;
}

note this will have some problems if more than 99 characters are entered for a string. try entering 100 or more characters for string 1, and see the result.

this case can be accounted for with a few extra lines of code. i'll leave that for you to figure out.


.

Edited 7 Years Ago by jephthah: n/a

Jeez have guys heard of "the good samaritan act", I'm sure the person thought he/she was helping. Did it require three senior posters calling this person down...

>Jeez have guys heard of "the good samaritan act", I'm
>sure the person thought he/she was helping.

He was helping, and I'm sure he can be a valuable asset to the forum. But not correcting the mistakes of good Samaritans would be grievous negligence on our part.

>Did it require three senior posters calling this person down...
Whatever it takes to get the point across.

I added mine because I thought I would be nice and supply you with an answer. Because also, your posted "solution" that "works" in Mandriva is not a viable solution: it's a platform specific workaround and an example of sloppy coding.

in any event, why are you complaining for getting help? you should be grateful that we're not letting you run with scissors.

fact is, Xavier666 is full of bad advice in a number of threads and I'm tired of seeing his "solutions". This one especially irks me because a moderator endorsed it.


.

Edited 7 Years Ago by jephthah: n/a

Jeez have guys heard of "the good samaritan act", I'm sure the person thought he/she was helping. Did it require three senior posters calling this person down...

I do not know what you mean by "did it require three senior posters calling this person down...", but if you are troubled by the amount of feed back those two "misguided" posts have produced, perhaps you are not understanding the purpose of the feed back in first place.

Edited 7 Years Ago by Aia: n/a

As everyone else had pointed out solution for, it better to you scanf function to read string or to reading anything at all. At least that my preference. But anyway, if you still used it make sure you flush the input stream before the second call of scanf function. The following code would help you in flushing the input buffer

void clear_buffer( void )
{
     int ch;
     
     while( ( ch = getchar() ) != '\n' && ch != EOF );
}

~ssharish

>The problem is that you have not flushed stdin. Put
>fflush(stdin); before the scanf . That should do it.
Yes, that should do it. "It" being break the program by invoking undefined behavior. Please don't recommend poor practices.

>Try using gets(str1); and gets(str2); in place of scanf()
Seriously dude, you should learn a little more about C before trying to help people. You're pushing the worst possible options. Have you never learned that gets is 100% unsafe and impossible to make safe?

I'm still learning. All of my teachers never reacted to my code like the way you people did but I guess that's because of their .. uh .. "inexperience".
No seriously, Narue, point noted about fflush(stdin)

Jeez have guys heard of "the good samaritan act", I'm sure the person thought he/she was helping. Did it require three senior posters calling this person down...

I'm really grateful for supporting me. I posted with all the best intentions

>Jeez have guys heard of "the good samaritan act", I'm
>sure the person thought he/she was helping.
He was helping, and I'm sure he can be a valuable asset to the forum. But not correcting the mistakes of good Samaritans would be grievous negligence on our part.

>Did it require three senior posters calling this person down...
Whatever it takes to get the point across.

Narue, I never need to be told twice about a mistake. One "scolding" would be enough.
And can you provide me a link where I can find the problems associated with scanf() and fflush() Please don't refer to "Starting C" because the thread has become too big

>All of my teachers never reacted to my code like the way you people
>did but I guess that's because of their .. uh .. "inexperience".

This is distressingly common. A large number of teachers don't know C well enough to teach it. What they know is either dreadfully outdated or closely tied to the implementation being used at the school.

>No seriously, Narue, point noted about fflush(stdin)
Excellent. I'll even offer a reasonably portable solution that comes close, so you don't feel pressured to use fflush(stdin):

void interactive_flush ( FILE *in )
{
  /*
    Don't flush the stream if it's in an "error" state because 
    flushing clears the state. It might be needed elsewhere
  */
  if ( !feof ( in ) && !ferror ( in ) ) {
    int ch;

    /* Line-oriented: a newline or EOF marks the end of interactive input */
    do
      ch = getc ( in );
    while ( ch != '\n' && ch != EOF );

    /* The above loop could put the stream in an "error" state */
    clearerr ( in );
  }
}

I say it's close because it doesn't work well when the stream is empty. There's no convenient portable way to query the number of characters in the stream, or make a non-blocking read, so if the stream is empty this function will block for input. However, fflush(stdin) is generally called only when one knows that there are extraneous characters that need to be discarded, so I don't see it as a big deal.

>Narue, I never need to be told twice about a mistake.
>One "scolding" would be enough.

That's nice, but keep in mind that we constantly have to deal with thick headed and/or stubborn people. It's not a slight against you personally. Rather, it means that we actually care enough about you and those you're helping to bother making corrections.

#include <stdio.h>

int main()
{
	char str1[100];
	char str2[100];

	printf("Enter 1st string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str1);

	printf("Enter 2nd string\n");
	fflush(stdin);
	scanf("%[^\n]s",&str2);

	printf("1st string is %s\n", str1);
	printf("2nd string is %s\n", str2);

	return 0;
}

Now, that you're better equipped with knowledge, let's take a look again at that scanf("%[^\n]s",&str1); . Narue told you already about the scanset and the extra s, however, the & has not been addressed.
Strings as parameters for scanf() are already pointers to the first element subscript, therefore str1 would be an implicit &str1[0]. &str1 is not.

i will give you my code:
and try to adopt it on your code

#include <stdio.h>

void clear_kb(void);

main ()
{
      int age;
      char name [20];
      /* prompt for user's age. */
     puts("Enter your age.");
     scanf("%d", &age);

    /* clear stdin of any extra characters. */

    clear_kb();

   /* now prompt for user's name. */
   puts("Enter your first name.");
   scanf("%s", name);
   
  /* Display the data. */

  printf("your age is %d,\n", age);
  printf("your name is %s.\n", name);
  return 0;
}

void clear_kb(void)
{ char junk[80];
   gets(junk);
}

Edited 7 Years Ago by __avd: Added [code] tags. Encase your code in: [code] and [/code] tags.

Comments
Well said.
Next time, try to read a thread before replying
get this shit out of here
gets() is not an option

i will give you my code:
and try to adopt it on your code

Yes, I did adopt it into my code. I kept the opening { and the closing }, in between I used the delete key.

Edited 7 Years Ago by Aia: n/a

i will give you my code:
and try to adopt it on your code

...
void clear_kb(void)
{ char junk[80];
   gets(junk);
}

You should really read the thread you are posting in. You would have learned something about gets()

Hi,

I Hope none of the above remarks would have solved your problem. I also actually faced this problem sometime ago. I think what you are missing is that after scanning string you are pressing either enter or space to take it as input. Next scanf("%s",&str2) will read that space or enter entered by you. Thats why it is not accepting your choice. So leave a blank space after %s in scanf() like scanf("%s ",&str1); or use a getchar() function after scanf("%s",&str1); statement. That will solve your problem.
Also you need not to put '&' before str1 and str2 as they already point to the starting location str1[0] and str2[0] .

Regards
Cheshar
:)

Edited 6 Years Ago by chesha: n/a

this one will solve your problem.

#include <stdio.h>

int main()
{
     char *str1[100];
     char *str2[100];

    printf("Enter 1st string\n");
    scanf("%s",&str1);

    printf("Enter 2nd string\n");
    scanf("%s",&str2);
  
   printf("1st string is %s\n", str1);
   printf("2nd string is %s\n", str2);
 
  return (0);
}

This one also will solved your problem.

#include <stdio.h>

main()
{
     char *str1[100];
     char *str2[100];

    printf("Enter 1st string\n");
    scanf("%s",&str1);

    printf("Enter 2nd string\n");
    scanf("%s",&str2);
  
   printf("1st string is %s\n", str1);
   printf("2nd string is %s\n", str2);
 
  return 0;
}

Edited 6 Years Ago by phpbeginners: n/a

If you have no idea what you are doing, please stop posting garbage like this:

this one will solve your problem.

#include <stdio.h>

int main()
{
     char *str1[100];
     char *str2[100];

    printf("Enter 1st string\n");
    scanf("%s",&str1);

    printf("Enter 2nd string\n");
    scanf("%s",&str2);
  
   printf("1st string is %s\n", str1);
   printf("2nd string is %s\n", str2);
 
  return (0);
}

This one also will solved your problem.

#include <stdio.h>

main()
{
     char *str1[100];
     char *str2[100];

    printf("Enter 1st string\n");
    scanf("%s",&str1);

    printf("Enter 2nd string\n");
    scanf("%s",&str2);
  
   printf("1st string is %s\n", str1);
   printf("2nd string is %s\n", str2);
 
  return 0;
}

it is not a garbage run it.
both codes are working.

the difference in first code there is int main() return is (0) in the second code I remove the return value int in main and put return 0;

and some correction on his pointers.

are you called that as a garbage?

next time friend you think before you write. :-)

Comments
ignorance is not a bliss, but rather an embarrasment
Next time - you think before you write and show some respect dufus.

next time friend you think before you write. :-)

He did certainly think before writing. I would have not been so polite.
I summit you are not only a phpbeginner but a notevencstarter.

Edited 6 Years Ago by Aia: n/a

Hello Friends.
I read your entire post it is nice place to share a problem well you have not post your full code so it is difficult to find the problem so first post here full code(included Header file) so I will check it and reply you.

it is not a garbage run it.
both codes are working.

Only by luck, not by design.

the difference in first code there is int main() return is (0) in the second code I remove the return value int in main and put return 0;

Small potatoes.

and some correction on his pointers.

Bahahahahahaha. :D

are you called that as a garbage?

Yup. Care to count along with me?

char *str1[100];

Here, str1 is not a string. It is not a pointer to a string. It is an array of 100 pointers to what might be strings. Each of these 100 pointers is uninitialized.

What this means is you now have 100 pointers pointing to nowhere. You can't write to str1 . You can't write to &str1 . You can't write to str1[0] , str1[1] , ... str1[99] . You first would need to point these pointers to somewhere that you can write.

scanf("%s",&str1);

Now, the scanf call you use will attempt to write to &str1 , which, as I mentioned above, is not yet ready to have anything written to it.

Technically, at this point your whole program is now "undefined". It could by chance appear to work as you intended. Or it could segfault and crash.

You have also muffed any attempt to provide the correct type information to scanf , which for the %s directive expects a pointer to char . The & would be superfluous and make the type incorrect if you had actually, somehow - perhaps by accident, declared str1 correctly. It would look like this:

char str1[100];
    printf("Enter 1st string\n");
    scanf("%s",str1);

Oh, wait! That was the whole point of your post. Taking the original correctly-declared version and uncorrecting it. Or maybe to introduce the whitespace-delimited issues of %s that it would appear that the original seemed to be trying to avoid.

next time friend you think before you write. :-)

You first. :)

Frankly, what you wrote as a "correction" should be discarded as junk by a Week 1 (if not Day 1) programmer in some introduction to C.

In this thread already there has been mentioned some of the issues regarding user input with scanf and gets . You seem to do to opposite of generally accepted good practice and instead recommend bad practice. Learn C before attempt to help others. Reread this thread and try to learn from it.

Comments
Nice.

Hi Dave Sinkula?

May be you do not know that.

*(array) == array[0]
*(array+1) == array[1]
*(array+2) == array[2]
*(array+n == array[n]

putting * in str[100] is not a luck.

What's wrong with that. BWAHAHAHAHAHAHA!

Try that an you will see...

TAKE NOTE!!!!! An array name without brackets is a pointer to the array's first element.

Meaning an array name s a pointer. BWAHAHAHAHAHA!!!

POOR DAVE BWAHAHAHAHAHA!

how come it is declaring no where? BWAHAHAHAHAHA!!!


it is just an array of pointers to characters.

char *str[100];

Am I right? BWAHAHAHAHAHAHA!

Edited 6 Years Ago by phpbeginners: n/a

Comments
It is human to err, but stupid to maintain the error.
This article has been dead for over six months. Start a new discussion instead.