I am trying to write a C program that takes n as an integer input and then inputs n strings. The problem that when I run the program, it takes one input less than n. If I enter 1 as the first input the program just terminates. Here is the code :
int n;
scanf("%d", &n);
char str[101];
while (n--) {
fgets(str, 101, stdin);
// other stuff...
}
What am I doing wrong here?
Your program will work if you use scanf() for the number and the string input.
#include <stdio.h>
int main()
{
int n;
char str[101];
scanf("%d", &n);
while (n--)
{
scanf("%s", str);
}
return 0;
}
But it's arguably better to use fgets() for all the inputs.
#include <stdio.h>
int main()
{
int n;
char str[101];
fgets(str, 100, stdin);
sscanf(str, "%d", &n);
while (n--)
{
fgets(str, 100, stdin);
}
return 0;
}
I scarcely need to remind you since you used fgets() in the first place, you'll be aware that it retains the newline at the end of the input string.
Remember that hitting the enter key sends a character to the stream too. Your program fails to account for this. Use the format scanf(%d%*c) to discard the second character.
int main(void) {
int n;
scanf("%d%*c", &n);
char str[101];
while (n--)
{
fgets(str, 101, stdin);
// other stuff.....
}
}
int n;
scanf("%d", &n);
char str[101];
while (n--)
{
fgets(str, 101, stdin);
// other stuff...
}
In this as you enter n and press ENTER from keyboard '\n is stored in stdin therefore as fgets encounters newline character if returns .
Therefore use this after scanf-
char c ;
while((c=getchar())!=NULL && c!='\n');
Related
So I need to write a function which counts the frequency of a character in a string in C. The function parameters must be just the character I want to count. So here's my code:
#include <stdio.h>
#include <string.h>
int charFrequency(char c) {
char str[500];
int i, nr = 0;
printf("Enter the string: ");
fgets(str, sizeof(str), stdin);
for(i=0; i < strlen(str); ++i) {
if (str[i] == c) {
nr++;
}
}
return nr;
}
int main(void) {
char c;
int nr;
printf("Enter the character you want to count: ");
c = getc(stdin);
getc(stdin); // what is the role of this code line? if I delete this line the programs does not work anymore.
nr = charFrequency(c);
printf("The frequency is %d", nr);
return 0;
}
I have a problem when I read the character I want to count. I use getc but the program doesn't work fine. But if I write again getc(stdin) the program works fine.
I also tried with scanf but I have the same issue. Can someone explain me how getc works?
I try to get strings as many as the input value in c.
But a leading white space located first line is removed.
I had already use the fgets and scanset. I want the input and output to be the same.
fgets(str[i], 100, stdin);
scanf("%[^\n]%*c]", str);
Code
int n = 0;
scanf("%d\n", &n);
char str[10][100] = {0};
for (int i = 0; i < n; i++) {
fgets(str[i], 100, stdin);
}
Input
3
**
*
**
Output
**
*
**
What should I do?
You have to use getchar() after reading n because the newline character '\n' will remain in the input buffer and your fgets in for loop will read that and also remove \n from scanf.
Use following line of code:
int n = 0;
scanf("%d\n", &n);
getchar();
char str[10][100] = {0};
for (int i = 0; i < n; i++) {
fgets(str[i], 100, stdin);
}
remove the "\n" from scanf and add a getchar() to capture the newline.
scanf("%d", &n);
getchar();
I'm trying to make a program which returns the a number and a string with the elements in reverse order. I was able to do both, but I don't understand why there are some blank new lines when I print out the reversed string
I've also tried it with just a single word using the scanf function, and a blank line still appears
#include <stdio.h>
#include <stdlib.h>
int main()
{
char s[50];
int i, n, lastDigit, textLen=0;
printf("Enter a number: ");
scanf("%i", &n);
getchar();
printf("Enter the text: ");
fgets(s, 50, stdin);
printf("The reversed number is: ");
while(n > 0){
lastDigit = n%10;
n=n/10;
printf("\n%i", lastDigit);
}
printf("\nThe reversed text is: ");
while(s[textLen] != '\0'){
textLen++;
}
for(i=textLen; i>=0; i--){
printf("\n%c", s[i]);
}
return 0;
}
I expect:
T
e
s
t
But the actual output is:
T
e
s
t
From the manual page of fgets
fgets() reads in at most one less than size characters from stream
and stores them into the buffer pointed to by s. Reading stops after
an EOF or a newline. If a newline is read, it is stored into the
buffer.
So here
char s[50];
fgets(s, 50, stdin);
fgets() stores the newline character at the end of buffer s if it was read. To remove this trailing \n character use strcspn(). For e.g
char s[50] = {}; /* Initialize it */
fgets(s, 50, stdin);
s[strcspn(s, "\n")] = 0; /* remove the trailing \n */
textLen is the number of characters in string s. The first character printed is s[textLen], which is the NUL character at the end.
I have a problem with reading strings in c. When I add the gets() function in an if-instruction, the program stops.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n,i = 0;
char sir[2000],ch;
printf("Press you option: "); scanf("%d",&n);
if(n == 1)
{
printf("text: "); gets(sir);
printf("\nINPUT: ");
for(i = 0;i < strlen(sir);i++)
printf("%c",sir[i]);
}
return 0;
}
Any solution?
When I add the gets() function in an if-instruction, the program stops.
Look at the preceding code. Maybe you entered 1 Enter
printf("Press you option: ");
scanf("%d",&n);
scanf("%d",&n); consume the '1', but not the '\n'.
Later code does
printf("text: ");
gets(sir);
And then gets() reads that '\n' and returns with sir[0] == '\0', an empty string. This causes for(i = 0;i < strlen(sir);i++) to not iterate the body of the for() loop.
What to do?
Read a line of user input fgets() and then process that string. Note that invalid input, EOF and buffer overflow handling not addressed in this simple code example. That would be step 2.
char buf[80];
printf("Press you option: ");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%d",&n);
printf("text: ");
fgets(buf, sizeof buf, stdin);
buf[strcspn(buf, "\n")] = '\0'; // lop off potential \n
strcpy(sir, buf);
This is due to the C input buffer problem, just add one getchar() as shown, it will work, let me know for any other help.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n,i = 0;
char sir[2000],ch;
printf("Press you option: "); scanf("%d",&n);
if(n == 1)
{
printf("text: ");
getchar();
gets(sir);
printf("\nINPUT: ");
for(i = 0;i < strlen(sir);i++)
printf("%c",sir[i]);
}
return 0;
}
gets() is not preferred way to get the input from the user these days. As mentioned above please use fgets to read the input.
Coming back to your problem. Please fflush(stdin) in order to resolve your issue. Trying running the below code. i have just added fflush(stdin) and now the user input is taken by fgets() and no program stopping happens.
Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n, i = 0;
char sir[2000], ch;
printf("Press you option: "); scanf("%d", &n);
if (n == 1)
{
printf("text: ");
fflush(stdin);
gets(sir);
printf("\nINPUT: ");
for (i = 0; i < strlen(sir); i++)
printf("%c", sir[i]);
}
return 0;
}
Also please read and understand why we are using fflush and why we need to avoid gets() function going forward. Hope i have helped you. Thank you :)
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;
}