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);
Related
So, I am trying to write an strncpy function. I want user to input the number of characters to be copied from source. I am doing something wrong, but I can't understand what. This is what I tried to do:
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n, m;
char s1[4], s2[4], nstr[m];
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
strcpy(s1, s2);
printf("The original string is: %s\n", string);
printf("The copy of the original string is: %s\n", string);
printf("How many characters do you want to take from this string to create another string? Enter: \n");
scanf("%d", &n);
strncpy(nstr, s1, m);
printf("%s\n", nstr);
}
(On top I tried some strlen and strcpy functions.)
EDIT: I totally forgot to write what was the problem. Problem is I can't get the new string which is named nstr in my code. Even though I printed it out.
first of all, the whole code is just a bad practice.
Anyway, here is my take on your code which copies n characters of an input string to string_copy
#include <stdio.h>
#include <string.h>
#define ARR_SIZE 20
int main() {
char string[ARR_SIZE];
int n;
printf("Enter the string:");
gets(string);
printf("The length of the string is: %ld\n", strlen(string));
printf("The original string is: %s\n", string);
printf("How many characters do you want to take from this string to
create another string? Enter: \n");
scanf("%d", &n);
if(n > strlen(string)){
n = strlen(string);
printf("you are allowed to copy maximum of string length %d\n", n);
}
char string_copy[n];
strncpy(string_copy, string, n);
printf("%s\n", string_copy);
}
note that using deprecated functions such as gets() isn't safe. use scanf() or fgets() instead.
refer to why you shouldn't use gets()
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);
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;
}