I am trying to run the following code but the program accepts only one string and displays the output immediately without waiting for the second string to be entered. The program is for 2 string concatenation. Here is the code :-
#include <stdio.h>
main()
{
int i, j, len=0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",&name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",&abc);
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
len++;
name[len]=abc[j];
}
printf("\nThe Concatenated String Is =\t");
puts(name);
}
Use fgets instead of scanf, also you were incrementing len at the wrong place:
#include <stdio.h>
#include <string.h>
int main() {
int len = 0;
char name[100], abc[100];
printf("\nPlease Enter String 1 =\t");
fgets(name, 100, stdin);
len = strlen(name) - 1;
name[len] = 0;
printf("\nPlease Enter String 2 =\t");
fgets(abc, 100, stdin);
abc[strlen(abc) - 1] = 0;
strcpy(name+len, abc);
printf("\nThe Concatenated String Is =\t");
puts(name);
return 0;
}
Use the following scanf instead:
scanf("%[^\n]",name);
.....
scanf(" %[^\n]",abc);
Please refer to this scanf() manual page for more detail of how to use scanf().
You have to throw away the newline character ('\n').
Try:
while(getchar() != '\n')
continue;
after each scanf
I would like to suggest you not to use scanf. Better to use fgets instead.
By the way the reason that your program accepts only one string and displays the output immediately without waiting for the second string to be entered is the \n character left behind by the first scanf after pressing the Enter key. To eat up this newline character you may use gatchar() after first scanf.
printf("\nPlease Enter String 1 =\t");
scanf("%[^\n]c",name);
getchar();
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]c",abc);
Other two mistakes are:
1. Wrong increment of len
for(i=0; name[i]!='\0'; i++)
len++;
for(j=0; abc[j]!='\0'; j++)
{
name[len++]=abc[j];
}
2. Reason for weird output is the string is not NUL terminated. Add this line after second for loop.
name[len] = '\0'; // add this to null terminate your string.
Here is your working Code
should be
scanf("%[^\n]%*c", name);
printf("\nPlease Enter String 2 =\t");
scanf("%[^\n]%*c", abc);
for(i=0;name[i]!='\0';i++)
len++;
for(j=0;abc[j]!='\0';j++){
name[len]=abc[j];
len++;
}
name[len]='\0';
Related
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);
}
Ive got this program which im stuck with in which I am trying to receive the size of a string and following it, telling the user to input the letter by letter. Here is my code.
#include<stdio.h>
#include<stdlib.h>
int main(){
int size;
int i;
char letter;
printf("Your string's size is...?: ");
scanf("%d", &size);
char mystring[size] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
mystring[i] = letter;
}
printf("%s",mystring);
system("PAUSE");
return 0;
}
Thanks!
Two problems here.
First, the %c format specifier to scanf will read any character, including a newline. You need to put a space before it to absorb any newlines in the input buffer:
scanf(" %c", &letter);
Second, you don't null-terminate the string, nor do you leave enough space in the array to store the null terminator. Make the array one element larger, and add the null byte at the end:
char mystring[size+1];
for (i=0; i<size; i++){
...
}
mystring[size] = 0;
Two things:
First, you need to terminate the string with a \0-character. Otherwise, printf will result in undefined behaviour.
Second, note that scanf("%c",..) will probably consume a new line left in the buffer when a user presses "enter" after having entered a number (i.e. the size).
Write:
char mystring[size+1] ;
for (i=0; i<size; i++){
printf("Write a letter: \n");
scanf("%c", &letter);
if (i==0 && letter == '\n') {
i--;
continue;
}
mystring[i] = letter;
}
mystring[size] = '\0';
printf("%s",mystring);
This program is not giving the correct output; and it is taking input once instead of 't' times, while entering for the first time in the for-loop.
This problem is HEADBOB (https://www.codechef.com/problems/HEADBOB)
#include <stdio.h>
int main()
{
int t;
scanf("%d", &t);
for(t; t>0; t--)
{
int J=0, Y=0, N=0, I=0, len=0;
if(len==0)
scanf("%d", &len);
char ar[len];
for(J=0; J<len; J++)
{
scanf("%c",&ar[J]);
if(ar[J]=='Y')
Y++;
else if(ar[J]=='N')
N++;
else if(ar[J]=='I')
I++;
}
if(I>0)
printf("INDIAN\n");
else
{
if((Y&&!N)||(N&&!Y))
printf("NOT SURE\n");
else if(Y&&N) printf("NOT INDIAN\n");
}
}
}
INPUT:
NUMBER OF TEST CASES
NUMBER OF CHARACTERS
N NUMBER OF CHARACTERS
SAMPLE INPUT & OUTPUT OF ABOVE CODE:
INPUT:
5
5
NNYNN
OUTPUT:
NOT INDIAN
Check, if scanf("%c", &ar[j]) is reading whitespace characters! Think about
scanf(" %c", &ar[j]);
That means to skip all whitespace characters (space, tabs, \ns, etc).
Or even better:
scanf("%d", &len);
char ar[len + 1]; // + 1 for 0-termination
scanf(" %s", ar); // skip all whitespace characters, then read a string
Reading full string in one shot is a lot faster.
The problem is that the second scanf (scanf("%d", &len);) leaves a newline character in the standard input stream (stdin). This character is then consumed by the third scanf (scanf("%c",&ar[J]);) in the first iteration of the loop.
Changing
scanf("%d", &len);
to
scanf("%d%*c", &len);
will fix the problem. %*c tells scanf to read and discard a character.
I have been asked to modify a program to read characters rather than numbers.
i modified the array into a char array. changed the two "%d" to "%c" as below
void main (void)
{
char a[100];
int counter;
int b;
counter = 0;
printf("please enter the length of the array: ");
scanf("%d", &b );
while (counter != b)
{
printf("please enter character: ");
scanf("%c", &a[counter]);
counter++;
}
a[counter] = '\0' ;
counter = 0;
while (a[counter] != '\0')
{
printf("\n");
printf("%c",a[counter]);
counter++;
}
}
when i run this the program does this:
please enter the length of the array: (4)
please enter character: please enter character: (a)
please enter character: please enter character: (a)
a
a
() are used to indicate the user inputs.
would be really good if i could get some help.
You have to remember that scanf leaves the newline in the input buffer, so when you try to read a character it will that newline.
The solution is very simple: Tell scanf to read and discard leading whitespace, by adding a space in the format code:
scanf(" %c", &a[counter]);
/* ^ */
/* | */
/* Note space here */
I have done up to this
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
scanf("%s",str);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
I don't get all the ASCII values when I tried to compile it. Will you please tell me where is my mistake.
It stops where it encounters where you give space in input.
So if you entered
Hello World scanf will display ascii values of characters in Hello only.
Solution: use fgets
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
fgets(str, sizeof(str), stdin);
printf("ASCII values of each characters of given string: ");
while(str[i])
printf("%d ",str[i++]);
return 0;
}
First; indent your code correctly (on Linux you could use the GNU indent utility, or astyle).
Compile it with all warnings and debugging info (e.g. gcc -Wall -g). Learn how to use the debugger (gdb) to run it step by step.
Then, your scanf("%s", str); is dangerous (should at least be scanf("%99s", str);, see scanf(3)) ! You could get crashes or undefined behavior if the user enters a very long "word" of 200 characters (e.g. 200 times the digit 0). Alos notice that %s reads up to a space or blank-like character. I believe it is good habit to zero a buffer before reading it. So replace your scanf with
memset (str, 0, sizeof(str));
fgets (str, sizeof(str), stdin);
At last, you are not flushing the buffered stdout output (see stdio(3), setvbuf(3), fflush(3), etc...). Try perhaps
while(str[i])
printf("%d ",str[i++]);
putchar('\n');
fflush(stdout);
The last call to fflush is useless here, but it is a good habit (or else end every printf format string with a newline \n since stdout is often but not always line-buffered!)
scanf stops reading if there is a space in the input string. You can either uses fgets or do the follwing:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int i=0;
printf("Enter any string: ");
str[i] = getchar();
while(str[i]!='\n'){
str[i+1] = getchar();
i++;
}
str[i] = '\0';
printf("%s\n",str);
i=0;
printf("ASCII values of each characters of given string: ");
while(str[i]!='\0'){
printf("%d ",str[i++]);
}
return 0;
}
EDIT:
To find average of the string a asked by you in comments:
#include<stdio.h>
#include<string.h>
int main()
{
char str[100];
int sum=0;
int average=0;
int i=0;
printf("Enter any string: ");
str[i] = getchar();
while(str[i]!='\n'){
str[i+1] = getchar();
i++;
}
str[i] = '\0';
printf("%s\n",str);
i=0;
printf("ASCII values of each characters of given string: ");
while(str[i]!='\0'){
sum = sum + str[i];
printf("%d ",str[i++]);
}
// To calculate average
average = sum/(i-1);
printf("\nAverage = %d\n",average);
return 0;
}