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;
}
Related
(I am very new to C by btw)
My current code
#include <stdio.h>
char main()
{
char x;
printf("Please enter your first initial:",x);
scanf("%c",&x);
char string[100];
char y;
printf("Please enter your last name:",y);
scanf("%s",&y);
printf("Hello I am %c %s. Nice to meet you.",x,y);
return 0;
}
You can't use a char value with %s scanf formatting. That reads a null-terminated string, and char doesn't have a place for the null terminator.
Read the last name into the string variable, and use that.
char string[100];
printf("Please enter your last name:)";
scanf("%99s", string);
printf("Hello I am %c %s. Nice to meet you.", x, string);
I just started programming in C and I was wondering why I can't store a string with multiple words with scanf().
For example, I enter: "That's an example" and it's stores only the first word "That's"
My code:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", &string);
printf("You entered: %s", string);
return (0);
}
You can let scanf() read more than one word with the character class conversion specifier: %[^\n] will stop at the newline and leave it pending in the input stream. Note that you must tell scanf the maximum number of characters to store into the destination array to avoid undefined behavior on long input lines. When passing an array to scanf(), you should not pass its address as &string, but just pass string as arrays decays into a pointer to their first element when passed as a function argument.
Here is a modified version:
#include <stdio.h>
int main(void) {
char string[100];
int c;
for (;;) {
printf("Please enter something: ");
/* initialize `string` in case the `scanf()` conversion fails on an empty line */
*string = '\0';
if (scanf("%99[^\n]", string) == EOF)
break;
printf("You entered: %s\n", string);
/* read the next byte (should be the newline) */
c = getchar();
if (c == EOF) /* end of file */
break;
if (c != '\n')
ungetc(c, stdin); /* not a newline: push it back */
}
return 0;
}
Note however that it is much simpler to use fgets() for this task:
#include <stdio.h>
int main(void) {
char string[100];
for (;;) {
printf("Please enter something: ");
if (!fgets(string, sizeof string, stdin))
break;
/* strip the trailing newline, if any */
string[strcspn(string, "\n")] = '\0';
printf("You entered: %s\n", string);
}
return 0;
}
#include <stdio.h>
#define BUFF_SIZE 512
int main(void) {
char string[BUFF_SIZE];
printf("Enter something: ");
fgets(string, BUFF_SIZE, stdin);
printf("You entered: %s", string);
return (0);
}
fgets() is the best option
I think there's a problem in you scanf(); I recommend you to remove & from it. then your code should see like that:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
In the c language, there is no data type called a string.
A string is stored as an array of characters.
Moreover, the variable itself points to the first element of the array. Therefore, there is no need to use the '&' operator to pass the address.
So, all you have to do is the following:
int main(void) {
char string[100];
printf("Please enter something: ");
scanf("%s", string);
printf("You entered: %s", string);
return (0);
}
Don't use '&' in scanf function.
int main()
{
char string[100];
printf("Please enter something: ");
scanf("%[^\n]%*c",string);
printf("You entered: %s", string);
return 0;
}
According to https://man7.org/linux/man-pages/man3/scanf.3.html, %s will ignore white-space characters. To capture spaces you would have to use %c with the additional size of the input argument, or use %[ format. Check if scanf will add \0 byte to the end or not.
The console will not do anything after the user has entered a string.
I have got the code to work using char string="enteraword" and taking out the whole printf and scanf function, however I need the code to work with a scanf function.
#include <stdio.h>
#include <string.h>
int main()
{
char* string;
printf("Enter a word: ");
scanf("%s", string);
char c=string[1];
printf("The second letter in %s is %c", string, c);
return 0;
}
This code has undefined behavior, you're passing an uninitialized pointer to scanf(), asking it to store a string there.
Also, remember that %s will stop at whitespace, so it's very unclear what "terms" should mean here.
Try e.g.:
char string[1024];
if(scanf("%1023s", string) == 1 && string[0] != '\0')
{
const char c = string[1];
printf("The second letter of '%s' is '%c'\n", string, c);
}
I am very new to c programming, and for a school assignment I need to write a programm that takes a string as input and add the letters “ay” to each word that starts with a consonant at the front of this word. It is hinted that this should be done with strncpy and strcat.
this is the code that I wrote:
#include <stdio.h>
#include <string.h>
int main()
{
char myString[50];
char abc[26] = "bcdfghjklmnpqrstvwxyz";
char strA[50];
char strB[50];
char strC[150];
char ay[3] = "ay";
printf("** Welcome to the Double Dutch game **\nPlease enter a string: ");
scanf(" %[^\n]s", &myString);
int i, j;
for (i=0; myString[i]!='0'; i++) {
for(j=0; abc[j]!='\0'; j++) {
if(abc[j] == myString[i]){
if(myString[i-1] == ' '){
strncpy(strC, &myString[0], i);
strncpy(strB, &myString[i], 40);
strcat(strC, ay);
strcat(strC, strB);
myString[0] = '\0';
strcat(myString, strC);
strC[0] = '\0';
strB[0] = '\0';
}
}
}
}
printf("Result: %s", myString);
}
When i run this code it keeps giving the error * Buffer overlow detected *: /home/a.out terminated. I cannot find the mistake that I made. Hopefully someone can help me.
Thanks
Change this:
scanf(" %[^\n]s", &myString);
to this:
scanf(" %[^\n]", myString);
since %[^\n] conversion modifier is not a modifier for %s, they are independent. As a result, you can discard it.
Tip: Add the size of your array - 1, to prevent a possible buffer overflow, like this: scanf(" %49[^\n]", myString);
Does it not return an int or something?
This is a snippet of my code:
int wordlength(char *x);
int main()
{
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
printf("Word Length: %d", wordlength(word));
return 0;
}
int wordlength(char *x)
{
int length = strlen(x);
return length;
}
Function strlen is applied to strings (character arrays) that have the terminating zero. You are applying the function to a pointer to a single character. So the program has undefined behaviour.
Change this part:
char word;
printf("Enter a word: \n");
scanf("%c \n", &word);
to:
char word[256]; // you need a string here, not just a single character
printf("Enter a word: \n");
scanf("%255s", word); // to read a string with scanf you need %s, not %c.
// Note also that you don't need an & for a string,
// and note that %255s prevents buffer overflow if
// the input string is too long.
You should also know that the compiler would have helped you with most of these problems if you had enabled warnings (e.g. gcc -Wall ...)
Update: For a sentence (i.e. a string including white space) you would need to use fgets:
char sentence[256];
printf("Enter a sentence: \n");
fgets(sentence, sizeof(sentence), stdin);