I am trying to calculate the length of a string by using a function. I know there is a predefined function but I wanted to make my own one. But the problem here is whenever I am running this code, it returns the length of the name with a %. Like this:
~ >>> /home/******/Coding/strlen
Enter your name ==> Example
The length of your name is 7%
I am really confused why this is happening. Please figure me out with what is wrong with my code... I am using GCC Version 10.2.0
/*String Length Using Function*/
#include <stdio.h>
int find_length(char[]);
int main()
{
char name[20];
int l;
printf("Enter your name ==> ");
scanf("%s",name);
l = find_length(name);
printf("The length of your name is %d",l);
return 0;
}
int find_length(char tempname[])
{
int len=0, i;
for(i = 0; tempname [i]!='\0'; i++)
{
len++;
}
return len;
}
It seems your shell is adding the % to tell you that your program didn't print a newline character at the end of output.
Add newline character to your output to prevent that.
/* add \n to print a newline character */
printf("The length of your name is %d\n",l);
Related
I tried to scan and print the characters of array using below code but input characters are not matching with output characters
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
OUTPUT
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
Can anyone please clarify my doubt why is the output not matching with input
Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
scanf("%s", s); /* In lieu of using a loop */
if (strlen(s) < n) /* Just in case less characters are entered than was noted */
n = strlen(s);
for (i = 0; i < n; i++)
{
printf("%c", s[i]);
}
printf("\n");
return 0;
}
The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.
:~/C_Programs/Console/InputOutput/bin/Release$ ./InputOutput
enter the value of n:
7
start entering the characters:
ABCDEFG
ABCDEFG
You might give that a try.
Regards.
I want to write a program that, with the help of pointers, takes the names of a number of people from the input and receives one character from the input for each row of the array and prints the number of repetitions of that character in the array line.
#include <stdio.h>
int main () {
int n, i, j;
char str[30][30];
printf ("how many names?:");
scanf ("%d", &n);
int m = 0;
for (i = 0; i < n; i++)
{
char ch, *s;
scanf ("%s", str[i]);
gets (str[i]);
s = str[i];
ch = getche ();
while (*s) if (*s++ == ch) m++;
printf ("%d\n", m);
}
return 0;
}
This program is incomplete and wrong. I want to know how we can take a letter from each of the names separately from the input and get the number of repetitions after giving the name entries to the program.
input: 2** leonardo ** peter ** o ** p /////
output:
how many names?
2
please enter 1th name:
leonardo
please enter 2th name:
peter
Number of repetitions Which letter of the name 1 do you want?
o
2
Number ofrepetitions Which letter of the name 2 do you want?
p
1
You can define a struct say containing the name and the count of all characters.
struct name_st
{
char name[30];
int count[26];
};
Create an array of the struct objects like: struct name_st s[30];
Read each name in the for loop like scanf("%s", s[i].name);
For each name, after reading you can parse the name character by character and update the count for each character like s[i].count[s[i].name[j] - 'a']++;
Then in another for loop, read the character you want to display the count for in the ith name, and simply output the count for that particular character like printf("%d", s[i].count[c - 'a']);
I am trying to make a program that counts the number of letters that the user has input. When I run my program, it says error: expected ';' after expression on the line count_letters(){ // writing the function to count number of letters? Does a function need a semicolon at the end? I also feel that I am not approaching this problem correctly, can someone please enlighten me :(
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int count_letters(); //function to count letters
int number_of_letters; //length of the string input
int letterCount; // counter for number of letters in the string input
int main(void) {
string text = get_string("Text: "); // getting string input
number_of_letters = strlen(text); //storing the length of string here
printf("Number of letters: %i\n", letterCount); //printing the number of letters in the string input
count_letters() { // writing the function to count number of letters
for (int i = 0; i < number_of_letters; i++) {
if (isalpha(text[i])) {
letterCount++;
}
}
}
}
While you are free to use strlen to get the initial number of characters in text, it isn't necessary. In C, the last character in a "string" is the nul-terminating character '\0' (which has the ASCII value of 0). This is what differentiates a normal array of characters, from a string. It is how all string functions know when to stop scanning for characters.
So you don't need to know beforehand how many characters there are in a string. For example, take the string "hello" entered at the "Text: " prompt where you have declared.
string text = get_string("Text: ");
When you enter "hello" at the prompt:
Text: hello
The string is stored in memory as:
+---+---+---+---+---+---+
| h | e | l | l | o |\0 |
+---+---+---+---+---+---+
^
|
text
where the pointer text points to the address of the first character of the string in memory. Using the fact that a string ends with a nul-terminating character, you can simply scan forward from the start until your reach '\0' (equivalent to plain old 0).
You can use a for loop and iterate using indexes:
for (int i = 0; text[i]; i++)
// do whatever with the character text[i]
Or you can use a pointer and simply increment the pointer so it points to the next character in the string until the '\0' is reached:
string p = text;
while (*p) {
// do whatever with *p (the character at that address)
p++;
}
Putting the last version into your int count_letters (string s) function (that passes a pointer to your string as a parameter to the function) and returns an int representing the number of letters (including only [a-zA-Z]), your function reduces to:
int count_letters (string s)
{
int n = 0;
while (*s) /* while not the nul-character */
if (isalpha (*s++)) /* check if current is letter, advance ptr */
n++; /* increment letter count */
return n; /* return letter count */
}
You main() function, not needing to call strlen() then reduces to:
int main (void) {
string text = get_string ("Text: ");
printf ("Number of letters: %d\n", count_letters(text));
}
Putting it altogether and including the needed headers, you would have:
#include <stdio.h>
#include <ctype.h>
#include "cs50.h"
int count_letters (string s)
{
int n = 0;
while (*s) /* while not the nul-character */
if (isalpha (*s++)) /* check if current is letter, advance ptr */
n++; /* increment letter count */
return n; /* return letter count */
}
int main (void) {
string text = get_string ("Text: ");
printf ("Number of letters: %d\n", count_letters(text));
}
Example Use/Output
Compile and link with the libcs50.so and then, for example you would have:
$ ./bin/ltrcountcs50
Text: hello world
Number of letters: 10
Understanding what a "string" in C is (outside of the unfortunate choice of the typedef char* string; used by CS50), allows you to handle scanning over the characters in your string without needing to know how many characters are included beforehand. (and also helps you understand why failing to provide a nul-terminated string to any of the C string function that expect a nul-terminated string as a parameter results in Undefined Behavior -- they have no way of knowing when to stop scanning for characters).
Look things over and let me know if you have further questions.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int count_letters(); //function to count letters
int number_of_letters; //length of the string input
//initialize letterCount to 0 so that doing letterCount++ does not add 1 to a garbage value
int letterCount = 0; // counter for number of letters in the string input
//define string as a global value if you don't want to refer to it again and again by pass it as parameter or reference
string text;
void count_letters() { //since it's not returning anything, it's void not integer
for(int i = 0; i < number_of_letters; i++) {
if(isalpha(text[i])
letterCount++;
}
}
int main(void){
text = get_string("Text: "); // getting string input
number_of_letters = strlen(text); //storing the length of string here
printf("Number of letters: %i\n", letterCount); //printing the number of letters in the string input
}
Hope this helps. All the comments are there where any modifications are made
I might take your knowledge for being too basic, please forgive me if it is the case.
I believe you have made a small mistake possibly led by the way another language works. The problem lies in the way you have declared count_letters().
To properly declare a function in C, first get out of any existing function, then enter any variable type as a return type for your function, the name of your function, then, in parenthesis, your function's parameters. And after that, your function's code can be inserted between brackets, like you did.
Note you can also declare the function without the code, then put the code for the function lower.
And you might also want to declare your string externally to avoid dealing with pointers.
Here's an example of function declaration:
int foo(int amount)
Hence your code should look a little like this:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
void count_letters(); //function to count letters
int number_of_letters; //length of the string input
int letterCount; // counter for number of letters in the string input
string text;
int main(void) {
text = get_string("Text: "); // getting string input
number_of_letters = strlen(text); //storing the length of string here
count_letters();
printf("Number of letters: %i\n", letterCount); //printing the number of letters in the string input
}
void count_letters() { // writing the function to count number of letters
for (int i = 0; i < number_of_letters; i++) {
if (isalpha(text[i])) {
letterCount++;
}
}
}
Now please excuse me if I did not understand or answer your question correctly, it would be with pleasure I'd improve myself if I could get more detail. Lacking the cs50.h library, I cannot know for sure my code works.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
int count_letters(char *); //function to count letters
int main(void)
{
char* text = get_string("Text: "); // getting string input
printf("Number of letters: %i\n", count_letters(text)); //printing the number of letters in the string input
}
int count_letters(char *text)
{ // writing the function to count number of letters
int letterCount,number_of_letters; //length of the string input
number_of_letters = strlen(text); //storing the length of string here
for(int i = 0; i < number_of_letters; i++){
if(isalpha(text[i]))
{
letterCount++;
}
return letterCount;
}
I am new to c programming and would like to write a program which has the following requirement:
Input: The number of inputs n, then n input chars , for example, 3 welcome to hku
Output concatenated chars, for example, welcomehku
However, I discovered a problem that when I submit the codes as following to the c autochecking platform, the output is ~~~~welcometohku instead of welcometohku.
Would anyone like to give help on the issue? Thank you very much to all of you.
#include<stdio.h>
#include<string.h>
int main(){
int num; /* array with 50 elements */
int i = 0;
char iarray1[100];
/* read array */
scanf("%d", &num);
char iarray[num][100];
for (i = 0; i < num; i++) {
scanf("%s", iarray[i]);
}
/* print array elements in reverse order */
for (i = 0; i < num; i++) {
strcat(iarray1,iarray[i]);
}
//display the concatenated string
printf("%s",iarray1);
return 0;
}
You need to initialize iarray1
Try
char iarray1[100] = {0};
The reason is that an uninitialized iarray1 may contain any value. So when you do the first strcat it may happen the string you want to concatenate is appended to some gargabe value.
I'm new to C and have been set the following problem. I am to write a program where a string can be entered and stored, I should then enter two integer values which will then be used to remove characters from the string, afterwards the result should be printed. Once the program works it should be converted into a function.
I have created a program that will split the entered string into two strings which store the chars I want to keep in two buffers, afterwards the two strings are concatenated to give the resultant edited string. The problem I am having is that when I print the edited string I get random characters at the end and sometimes in between the two strings and I think it's because the strings are not being null terminated correctly. I hope that someone is able to help, Thanks :)
#include <stdio.h>
#include <string.h>
int main ()
{
char string [25];
char buffer1 [25];
char buffer2 [25];
int start;
int remove;
int i;
int finish;
int size;
int numbercopy;
int A, B, C;
printf("Enter a string: ");
gets(string);
printf("\nEnter a starting character position: ");
scanf("%d", &start);
printf("\nHow many characters would you like to remove? ");
scanf("%d", &remove);
finish = (start+remove);
size = strlen(string);
numbercopy = (size-finish);
strncpy(&buffer1[0], &string[0], start);
buffer1[start] = '\0';
strncpy(&buffer2[0], &string[finish], numbercopy);
buffer2[numbercopy] = '\0';
A = strlen(buffer1);
B = strlen(buffer2);
C = (A+B);
strcat(buffer1, buffer2);buffer1[C] = '\0';
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
return 0;
}
Since it is a string, you do not need to print it character by character. Also, the loop indicates that only 25 char strings will be printed. If a string (buffer1) is shorter in length(<25), garbage values will be printed, if a string is is larger (>25), some chars will not be printed.
Change this:
for (i=0; i<25; i++)
{
printf("%c", buffer1[i]);
}
to this:
printf("%s", buffer1);