I run the following c program
char str[80] = "String";
printf("hello %s\n", str);
scanf("%s", str);
printf("%s\n", str);
scanf("%[ABCDEF]", str);
printf("hello %s\n", str);
return 0;
For some reason on line 5 when it is suppose to input from Pattern %[ABCDEF], the console simply prints previous string (input from line 3). Why is that so?
Thats because the first scanf call doesn't read the newline character and the second call to scanf simply reads that newline character. To avoid this start the format string with a space like this:
#include <stdio.h>
int main(void)
{
char str[80] = "String";
printf("hello %s\n", str);
scanf("%s", str);
printf("%s\n", str);
scanf(" %[ABCDEF]", str);
printf("hello %s\n", str);
return 0;
}
However, you also need to make sure that str doesn't overflow if the user inputs a string longer than 79 characters.
Related
The source code file (test.c) copied below has my c code and
console output commented out.
I am trying to figure out why "Hello" is not printing to
console output.
I believe it may have something to do with scanf([^\n])
reading in a '\n' from previous line (see lines 14 & 15).
#include <stdio.h>
#include <string.h>
#define MAX_LEN 16
int main(){
char ch;
char s[MAX_LEN];
char sen[MAX_LEN];
scanf("%c", &ch);
scanf("%s", s);
scanf("\n");
scanf(" %[^\n]", sen);
scanf("%*c");
printf("%c\n", ch);
printf("%s\n", s);
printf("%s\n", sen);
printf("sen[15] = %c\n", sen[15]);
printf("string length = %lu\n", strlen(sen));
return 0;
}
Output
user#MacBook-18 c_the_hard_way % ./test
C
Hello
My name is Mikey
C
My name is Mikey
sen[15] = y
string length = 16
The problem is here:
#define MAX_LEN 16
The string length given:
My name is Micky
Has the length of 16 without a null-terminator. Change the MAX_LEN to 17.
If we make a couple of small changes, we can see why Hello is not being printed:
#include <stdio.h>
#include <string.h>
#define MAX_LEN 16
int main(){
char ch;
char s[MAX_LEN];
char sen[MAX_LEN];
scanf("%c", &ch);
scanf("%s", s);
scanf("\n");
scanf(" %[^\n]", sen);
scanf("%*c");
printf("%c\n", ch);
printf("%s\n", s);
printf("%s\n", sen);
// The null terminator from the second string is getting written
// to the start of the storage for "Hello"
printf("s[0] = %d\n", (int) s[0]);
// Let's try to print "Hello" now that we know what is happening
printf("%s\n", &s[1]);
printf("sen[15] = %c\n", sen[15]);
printf("string length = %lu\n", strlen(sen));
return 0;
}
Output
C
Hello
My name is Mikey
C
My name is Mikey
s[0] = 0
ello
sen[15] = y
string length = 16
Here, we see that the start of Hello is being overwritten by the null terminator from My name is Mickey.
Run this code online
Note
The language lawyers will be coming out of the woodwork to say that what you are experiencing is "undefined behavior" and that the output above is not guaranteed to be the same. However, in this case, the compiler implementations are similar enough that we get the same output.
I am trying to read two strings from the keyboard and print them.
Why does printf("read 1st\n") run after the second scanf()?
#include <stdio.h>
int main(void)
{
char str[20];
char str2[20];
scanf("%s", str);
printf("read 1st\n");
scanf("%s", str2);
printf("read 2nd\n");
printf("str: %s\nstr2: %s\n", str, str2);
return 0;
}
Expected:
foo
read 1st
bar
read 2nd
str: foo
str2: bar
Actual:
foo
bar
read 1st
read 2nd
str:foo
str2:bar
I could not reproduce your problem, but adding a fflush(stdout); should take care of your problem.
scanf("%s", str);
printf("read 1st\n");
fflush(stdout); // Ensures that the above is printed before scanf is executed
scanf("%s", str2);
printf("read 2nd\n");
I would also change the scans to scanf("%19s", str);. Otherwise, bad things could happen if you enter a string longer than str can hold.
I am new to C language and I am trying read a character and a string (a sentence; max-length 25) from a user.
Not sure what I am doing wrong in the following lines of code, its giving me an error "Segment Fault".
#include <stdio.h>
int main(){
char * str[25];
char car;
printf("Enter a character: ");
car = getchar();
printf("Enter a sentence: ");
scanf("%[^\n]s", &str);
printf("\nThe sentence is %s, and the character is %s\n", str, car);
return 0;
}
Thanks!
You have to make four changes:
Change
char * str[25];
to
char str[25];
as you want an array of 25 chars, not an array of 25 pointers to char.
Change
char car;
to
int car;
as getchar() returns an int, not a char.
Change
scanf("%[^\n]s", &str);
to
scanf( "%24[^\n]", str);
which tells scanf to
Ignore all whitespace characters, if any.
Scan a maximum of 24 characters (+1 for the Nul-terminator '\0') or until a \n and store it in str.
Change
printf("\nThe sentence is %s, and the character is %s\n", str, car);
to
printf("\nThe sentence is %s, and the character is %c\n", str, car);
as the correct format specifier for a char is %c, not %s.
str is an array of 25 pointers to char, not an array of char. So change its declaration to
char str[25];
And you cannot use scanf to read sentences--it stops reading at the first whitespace, so use fgets to read the sentence instead.
And in your last printf, you need the %c specifier to print characters, not %s.
You also need to flush the standard input, because there is a '\n' remaining in stdin, so you need to throw those characters out.
The revised program is now
#include <stdio.h>
void flush();
int main()
{
char str[25], car;
printf("Enter a character\n");
car = getchar();
flush();
printf("Enter a sentence\n");
fgets(str, 25, stdin);
printf("\nThe sentence is %s, and the character is %c\n", str, car);
return 0;
}
void flush()
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
;
}
// This is minimal change to your code to work
#include <stdio.h>
int main(){
char car,str[25];
printf("Enter a character: ");
car = getchar();
printf("Enter a sentence: ");
scanf("%s", str);
printf("\nThe sentence is %s, and the character is %c\n", str, car);
return 0;
}
just having a little issue with strtok and strcmp.
I'm trying to compare the input of a user via fgets to some predetermined string:
char *token[100];
fgets(s, sizeof(s), stdin)
token[0] = strtok(s, " "); // Get first word
printf("tok: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo");
Obviously it's not all the code but this shows my problem - if I enter "/bin/echo ..." (or anything for that matter), it will be put into token[0], and get printed. It prints correctly but when it prints the cmp value it's never 0. For /bin/echo, the cmp value is 1 for some reason.
Thanks.
EDIT to clear up confusion about s and token:
char s[1024];
char *token[100];
EDIT 2 - Added some other test cases:
I entered "/bin/echo hello world" to stdin
token[0] = strtok(s, " \n\0"); // Get first word
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
Output:
token[0] is: /bin/echo
cmp: 1
And then I tried hardcoding the tokened string:
char str[] = "/bin/echo hello world";
token[0] = strtok(str, " ");
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
Output:
token[0] is: /bin/echo
cmp: 0
here i have made small program
#include<string.h>
#include<stdio.h>
int main()
{
char str[] ="/bin/echo this is something";
char * token[100];
token[0] = strtok (str," ");
token[0] = strtok(str, " "); // Get first word
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
return 0;
}
Here i have statically stored input string instead of fgets()
That works fine.
see http://codepad.org/IrGAXT8f
Use
char token[1000];
strcpy(token,strtok(s," "));
string's can't be assigned directly like this in c :)
also, include string.h
One needs to allocate memory dynamically for copying strings. Read about dynamic memory management first (malloc, calloc, etc...)
EDIT:
http://ideone.com/0UxEwO - works for me
#include <stdio.h>
#include <string.h>
int main()
{
char s[1024];
char *token[100];
fgets(s, sizeof(s), stdin);
token[0] = strtok(s, " \n\0");
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
}
I have the following code:
char *s1, *s2;
char str[10];
printf("Type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%s\n", s1);
printf("%s\n", s2);
When I run the code, and enter the input "A 1" as follow:
Type a string: A 1
I got the following result:
A
�<�
I'm trying to read the first character as a string and the third character as an integer, and then print those out on the screen. The first character always works, but the screen would just display random stuffs after that.... How should I fix it?
You're on the right track. Here's a corrected version:
char str[10];
int n;
printf("type a string: ");
scanf("%s %d", str, &n);
printf("%s\n", str);
printf("%d\n", n);
Let's talk through the changes:
allocate an int (n) to store your number in
tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf
That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.
scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.
Try this code my friend...
#include<stdio.h>
int main(){
char *s1, *s2;
char str[10];
printf("type a string: ");
scanf("%s", str);
s1 = &str[0];
s2 = &str[2];
printf("%c\n", *s1); //use %c instead of %s and *s1 which is the content of position 1
printf("%c\n", *s2); //use %c instead of %s and *s3 which is the content of position 1
return 0;
}