I am learning C, and the problem I am running into is if I iterate through the string up to and including strlen(), I am expecting to get the null character (nothing) printed, but instead, I just keep getting '.' — whereas if I print array[strlen(array)], I get nothing (null character). What is going on?
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
char *mystring;
printf("Enter a string: ");
mystring = GetString();
//Prints '.' for mystring[i] when i = strlen(mystring)
for (int i = 0, j = strlen(mystring); i <= j; i++){
printf("The %dth character is: %c.\n", i+1, mystring[i]);
}
//Skips the line printing nothing ('\0')
printf("The last char is %c\n", mystring[strlen(mystring)]);
return 0;
}
You are actually printing this dot every time (right after %c): "The %dth character is: %c.\n". When your input is the null character %c won't print a thing since it's null and all you see is the dot afterwards.
For \0 nothing will be printed. But you have . after %c in printf statement-
printf("The %dth character is: %c.\n", i+1, mystring[i]);
Due to that ., when printing \0 it will print only .(For null it wont print anything).
printf("The %dth character is: %c\n", i+1, mystring[i]); //remove that . and try!
Related
#include <stdio.h>
#include<string.h>
int main(void)
{
int n,u = 0;
printf("Enter length of word ");
scanf("%d",&n);
char word[n*2];
printf("Enter the String \n");
scanf("%s", word);
printf("string that u have entered: %s\n",word);
int i = n - 1, j = n;
while(i >= 0)
{
printf("word[i-1] %c\n",word[i]);
word[j] = word[i];
printf("i %d\n",i);
printf("j %d\n",j);
i--;
j++;
}
printf("reversed word stored at the last in the same array - %s\n",word);
}
when we give the length 3 the output doesn't give any garbage value in output but when I give greater than 3 its starts to give garbage value in the output. (yeah I know we have to add '\0' at the end of the array to stop but for length 3 without that, it works.)
Here, you have declared the word as char array and alloted the size of array. So,when you are printing via indexing of array as %c --it gives the correct result. But,at the end,when you try to print the whole 'word' char array, you used %s . Now, what %s does is : when you indicate to a string, it stores the address of the first element and keep printing the value stored in those addresses in sequential manner untill it finds the null value. So,you better use a loop to print values stored in 'word' array using %c or you can convert your char array 'word' into string & then use %s to print values inside 'word'.
I am just running a code to find the length of a given string input by the user in C programming language. I used a loop condition to determine the length but statements inside loop executes when the condition is false also. The code I have tried in c is:
#include <stdio.h>
#define ArrayLength 50
int StringLengthCount();
int main() {
printf("Hello, World!\n");
/*Question: Find inserted string's length, without build in function*/
int c=StringLengthCount();
printf("Your inserted string's length is:%d",c);
return 0;
}
int StringLengthCount(){
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1,ArrayLength,stdin);
printf("Your inserted string is:%s\n",array1);
int i=0;
int count=0;
while(array1[i]!='\0'){
count++;
printf("%d character is %c",count,array1[i]);
printf("\n");
i++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d",count);
}
I am expecting the result 2 for a sample string input "we", but it gives result 3.
The output result in CLion compiler is given below
enter image description here
Can you kindly tell me why it happens?
If by "statements inside loop executes when the condition is false also" you mean that you see an extra character every time you execute remember that also the line feed (LF alias \n) character that you use to enter your string is part of the acquired string.
So even the empty string has one character that is \n or 0x10.
Your check should be something like this:
while (array1[len] != '\0' && array1[len] != '\n' )
And you function, as suggested in the comments, should have a return and could use just one variable like this:
int StringLengthCount() {
printf("\n");
printf("Please enter a sentence to find its length of character:");
char array1[ArrayLength];
fgets(array1, ArrayLength, stdin);
printf("Your inserted string is:%s\n", array1);
int len = 0;
while (array1[len] != '\0' && array1[len] != '\n' ) {
printf("%d character is %c", len + 1, array1[len]);
printf("\n");
len++;
}
printf("\n");
printf("Your inserted string's total character i.e string length is:%d\n\n",
len);
return len;
}
The function fgets will also read the newline character, so you need to change the condition in the while-loop from str[i] != '\0' to str[i] != '\n'. I have also implemented the suggested changes by Devolus.
#include <stdio.h>
#include <stdlib.h>
#define LEN 50
void string_length();
int main(void)
{
string_length();
return EXIT_SUCCESS;
}
void string_length(void)
{
printf("Enter a string: ");
char str[LEN];
fgets(str, LEN - 1, stdin);
printf("Your entered string is: %s\n", str);
int i = 0;
while (str[i] != '\n') {
printf("The %d. character is '%c'.\n", i + 1, str[i]);
++i;
}
printf("\nThe string's length is %d.\n", i);
}
I'm new in programming and I'm facing the problem where the program has to ask the user to enter as much numbers as he wants and store them in a variable, then print all the digits until a 0 is found.
The only thing i could think of was to store the scanf() in a char*, then try to print all digits until a 0 is found, but i end up with a segmentation faults...
here's my code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char *argv[]){
char entry[50];
printf("Enter a number !\n");
scanf("%c", &entry); // maybe %d or %s ?
printf("\n");
int i=0;
while (entry[i] != 0){
if (entry[i] !=0){
printf("%c", entry[i] ); // maybe %d with, (int)entry[i] ?
}
i++;
}
return 0;
}
Edit : It works now, had to fix (entry[i] != 0) --> (entry[i] != '0') and the scanf's %c --> %s.
You could read it as string (%s) and compare until the current character is character 0:
while (entry[i] != '0') {
Characters go between single quotes in c.
You could get the same result comparing with the integer 48 as 48 is the ASCII code of 0 and it's how the char is stored internally but it's more readable and easy to understand comparing it to '0'.
And that if inside the while is not necessary as it's going to be always true.
Is there a simple way to make sure you're reading a character through scanf. If it were an integer I'd use a do while loop
do{
printf("enter a number");
fehler = scanf(" %d", &x);
getchar();
} while(fehler!=1);
But I'm not fully sure what to do if the input is meant to be a string. I know the alphabets are stored as ASCII values but the if constraints in the while statement don't seem to be working(unless I'm doing it wrong)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s", temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
You can't compare a string to a single character. You have to loop through the entire string, checking every character.
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s", temp2);
getchar();
} while(!is_alphabetic(temp2));
You see printf and scanf work independently. Whatever you store be it a character or number is stored in form of a number. Now it depends on the printf function what it demands.
Eg.: If you store 'a' at a location, the number 97 is stored. Now if you print a number it prints 97 and if you demand a character it gives a.
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n", i);
printf("%c", i);
return 0;
}
See the results. Further char, int , long int are just data types which specify the number of bits that would be resrved for the inputs for the variable.
Execute this program and you'll understand:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will show you a nmber when printed as a number and then the SAME number read as character.
Note there are no markers in memory to store which type of data it is. It is straightforward stored as number.
scanf is absolutely the wrong tool for this. But if you want to read only alphabetic characters, you can do it easily enough with something like:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]", s) ){ ... }
The %31[a-zA-Z] conversion specifier will match only the literal characters a thru z and A thru Z, and will only consume up to 31 characters of input. You must always use a field width modifier with %s or %[] conversion specifiers to avoid an overflow.
I mixed up two programs in the cs50 sandbox, one was to find the the number of characters in an array and other was the print these characters. I know the program is garbage but could anyone explain me what is the compiler doing here?
When I ran this, the output starts printing alphanumeric text and never stops Thanks
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Name: ");
int n = 0;
while (strlen(s) != '\0')
{
n++;
printf("%c", n);
}
}
You have multiple problems with the code you show, here's a couple of them:
strlen(s) will never be zero as you never modify or remove characters from the string, which means you have an infinite loop
n is an integer and not a character so should be printed with the %d format specifier
'\0' is (semantically) a character, representing the string terminator, it's not (semantically) the value 0
To fix the first problem I suspect you want to iterate over every character in the string? Then that could be done with e.g.
for (int i = 0; i < strlen(s); ++i)
{
printf("Current character is '%c'\n", s[i]);
}
But if all you want is to could the number of characters in the string, then that's what strlen is already gives you:
printf("The number of characters in the string is %zu\n", strlen(s));
If you want to count the length of the string without using strlen then you need to modify the loop to loop until you hit the terminator:
for (n = 0; s[n] != '\0'; ++n)
{
// Empty
}
// Here the value of n is the number of characters in the string s
All of this should be easy to figure out by reading any decent beginners book.
while (strlen(s) != '\0') is wrong. '\0' equals 0. There string length is never 0, so the loop keeps going on forever, printing integers interpreted as characters.
You can either use the indexes to go through the string characters by using the variable "n" or you can increment the pointer of the string that you have received from the standard input to go through all of its characters.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
string s = get_string("Name: ");
/* First way using n to iterate */
int n = 0;
for (n = 0; n < strlen(s); ++n)
{
printf("%c", s[n]);
}
printf("\n");
/* Second way increment the string pointer*/
while (strlen(s) != '\0')
{
printf("%c", *s); //print the value of s
s++; // go to the next character from s
}
printf("\n");
return 0;
}