-
string question
I would like to input a whole name (including spaces), Here's what I have so far:
#include <stdio.h>
char name[50];
int main(void)
{
scanf("%s",name);
printf("%s",name);
return 0;
}
If I were to enter John Doe, only John would come out of the print statement. How do I "Doe"?
-
fgets( name, 50, stdin );
or
scanf( "%[^\n]", name );
-
I tried using those but when I run the program, it never gives me the chance to input the information. It just flashes by...Did I need to do something else?
-
er, Nevermind. Got it going. Thanks for your help!
-
Ok...this is the code that's not working well for me so far. I assume it's a problem with my function calls since I see that the scanf is working correctly. Where am I going wrong? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
char name[50];
int selection;
int main(void)
{
scanf("%d",selection);
switch(selection)
{
case 0:
write_name();
break;
default:
break;
}
return 0;
}
int write_name(void)
{
clrscr();
printf("What is your name?");
scanf("%[^\n],name);
printf("\n%s",name);
return 0;
}
-
Salem, what is this mean?
Code:
scanf( "%[^\n]", name );
I know scanf, but what is %[^\n]? I can see the newline (\n), but I don't understand the rest. Thanks.
-
I think scanf() cannot read spaces, you would have to have two seperate scanf() functions to read the first then last name.. Could be wrong though, Im reading this from an out-of-date book hehe
-
try
works like a charm for me
-
I tried gets(name), but upon execution, it doesn't let me input information. I'm not sure what I'm doing wrong here.
-
This could work!
Try something like
cin.getline(name,lenght_of_the_name_field,"\n");
Oh, by the way...
I think, that you have to include
#include <iostream.h>
also!
Have a nice weekend...
-
cin.getline is c++ not c.
scanf( "%[^\n]", name );
will read until a newline is encountered. For that reason you'll have to clear the buffer before using it -
Code:
#include <stdio.h>
#include <stdlib.h>
char name[50];
int selection;
int write_name(void)
{
int c;
// clrscr(); doesn't work on my compiler
printf("What is your name?");
while ((c = getc(stdin)))
if (c == '\n')
break;
scanf("%49[^\n]",name);
printf("\n%s",name);
return 0;
}
int main(void)
{
scanf("%d",&selection);
switch(selection)
{
case 0:
write_name();
break;
}
return 0;
}
-
Yay! It works! Thanks!!!! :)