How to read a first string with leading white space in c? - c

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();

Related

Unexpected line break in printf in c

I'm learning string in c, and i'm working on my homework which ask me to write a program to replace part of string under certain circumstances. Here is my source code(undone):
#include <stdio.h>
#include <string.h>
int main()
{
char str1[128], str2[128], str3[128];
for (int i = 0; i < 128; i++) //initialize str
{
str1[i] = 0;
str2[i] = 0;
str3[i] = 0;
}
printf("Input the first string:"); //inputs
fgets(str1, 128, stdin);
printf("Input the second string:");
fgets(str2, 128, stdin);
printf("Input the third string:");
fgets(str3, 128, stdin);
if (strncmp(str1, str2, strlen(str2) - 1) == 0) //if the first n charters match (n=length of str2)
{
printf("%s", str3); //print str3
int RemainingChar = 0;
RemainingChar = strlen(str1) - strlen(str2);
for (int i = 0; i < RemainingChar; i++)
{
printf("%c", str1[i + strlen(str2) - 1]); //print the remaining part
}
}
return 0;
}
Here is how it run:
Input the first string:asdfghjkl
Input the second string:asd
Input the third string:qwe
qwe
fghjkl
There is an unexpected line break. what should I do to make it output like this:qwefghjkl?
The function fgets will also store the newline character '\n' at the end of the line into the string. If you don't want this newline character to be printed, then you must remove it before printing the string.
See the following question for several ways to remove the newline character:
Removing trailing newline character from fgets() input

How to prevent fgets() from picking \n as input? [duplicate]

This question already has answers here:
Removing trailing newline character from fgets() input
(14 answers)
Closed 2 years ago.
The book_name is picking \n as input a printing the next variable in a new line. I inserted this code while ((getchar()) != '\n'); to prevent fgets() from taking \n as input after using scanf(). But i can't understand why fgets() is taking \n as input. Please explain.
CODE
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char *book_name;
char *author;
} book;
int main() {
int n;
printf("Enter number of books: \n");
scanf("%d", &n);
book *bk = calloc(n, sizeof(book));
for (int i = 0; i < n; i++)
{
printf("Enter the no of the book: \n");
scanf("%d", &((bk+i)->id));
while ((getchar()) != '\n');
(bk+i)->book_name = malloc(20);
printf("Enter the name of the book: \n");
fgets((bk+i)->book_name, 20, stdin);
(bk+i)->author = malloc(20);
printf("Enter the author of the book: \n");
fgets((bk+i)->author, 20, stdin);
}
for (int i = 0; i < n; i++)
{
printf("%d %s %s\n", (bk+i)->id, (bk+i)->book_name, (bk+i)->author);
}
return 0;
}
OUTPUT
Output of code
Check answered post here.
scanf() leaves '\n' in the buffer. So whenever any other function such as getchar() or fgets() tries to read from the stdin, leftover '\n' is read first.
If you are on file instead of stdin, better use below code for extra safety.
FILE *fp = fopen("my_file.txt", "r");
int c;
while ((c = fgetc(fp)) != EOF && c != '\n');
What you have done is the correct way to remove leftover \n, #sadbro probably misunderstood your code.

Why does my C program print new blank lines when I try to print a string in the reverse order?

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.

Want to store "char values" in array (in C language)

I want to store "char data type values" in an array, but it doesn't work.
First, I tried using "gets"
but it gave me a run time error.
Code was like this
int tmp = 0;
char arr[100] = { 0, };
while (arr[tmp]!=NULL)
{
gets(arr[tmp]);
tmp++;
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%s ", arr[rtmp]);
return 0;
In a second way, I was using "scanf", but I couldn't store "char data type(it should be more than one character like string)", but only one character was available.(I tried %s, but it doesn't work)
Plus, it doesn't print the last value of array.
int a = 0;
scanf("%d", &a); //determine how much I input values
int tmp = 0;
char arr[100] ={ 0 , };
for(tmp=0;tmp<a;tmp++)
{
scanf("%c ",arr[tmp]);
fflush(stdin);
}
for (int rtmp = 0; rtmp < a; rtmp++)
printf("%c ", arr[rtmp]);
return 0;
The most "identical" for me is
without notifying "a" values("a" means how much values I input)
and storing "char values" in array..
How can I solve this problem?
Thanks in advance! Your help is always appreciated :)
Array of char data type is called Sting. You can take a string's input using scanf() and gets(). But if you use scanf(), the string will be input by pressing Space-bar or Enter. But if you use gets(), input will be given only by pressing the Enter key.
Example 1:
char s[100];
scanf("%s", s);
Example 2:
char s[100];
gets(s);
Now, if you want to input every single character individually, you can do that also:
char s[100], c;
int n, i, j;
scanf("%d", &n);
getchar();
for(i=0; i<n; i++) {
scanf("%c", &s[i]);
}
s[i] = '\0';
Now look, I wrote a getchar() after scanf("%d", &n);, because when you press enter after inputting n, a new line character ('\n') is also taken as input in the character next to n. So you must do this in case like this.
One more thing, you can take input any string containing spaces using scanf() also. Just do this:
char s[100];
scanf("%[^\n]", s);
You can not enter the individual character by following snippet of code.
char arr[10] = {0};
//unsigned char ch;
unsigned int i = 0;
printf("Enter the array elements\n");
for(i = 0; i<10; i++)
{
scanf("%c", &arr[i]);
printf("i = %d and arr[%d] = %c\n", i, i, arr[i]);
}
The result of this snippet is as per this image. enter image description here
To avoid this issue, it is recommended to enter the character without new line charactoer '\n' or without pressing enter.
Or other method is to use the array as string and input the character by gets() like this snippet.
char s[100];
gets(s);

Issues while inputting strings in C

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');

Resources