How can i print empty spaces from a string? - c

#include <stdio.h>
int main(){
char phrase [100]={0};
printf("Write a sentence: \n");
scanf ("%s", phrase);
printf("%s\n", phrase);
}
The purpose of this program is to print a sentence from the user. The problem is that there is something wrong with the ' ' character and i dont know how to solve it.
During the execution, the sentence is only printed until the first empty space, for some reason. but why?

As pointed out in comments, the %s conversion specifier in scanf can't read strings with white spaces; it uses white spaces as delimiters. You can use fgets :
#include <stdio.h>
#include <string.h>
int main() {
char aLine[100];
fgets(aLine, 100, stdin);
aLine[strlen(aLine)-1] = '\0'; // trimming the last \n
printf("%s\n", aLine);
return 0;
}

Related

When I try to print the string inputted by the user in the console and then print the same inputted string;the first word gets omittedl. How do i fix?

As you can see in the above mentioned title , I don't know if there is something I am doing wrong . I have just started learning c . Please help me with the code.
#include <stdio.h> //code in c language.
#include <string.h>
int main()
{
char str[20];
printf("Enter the string:");
scanf("%s",&str);
gets(str);
printf("The string is: %s \n",str);
printf("The reverse string is : %s",strrev(str));
return 0;
}
In order to get the complete string from stdin, its recommended to use fgets like follows:
#include <stdio.h> //code in c language.
#include <string.h>
int main()
{
char str[20];
printf("Enter the string:");
/* strtok removes trailing newline character from fgets() */
strtok(fgets(str, 20, stdin), "\n");
printf("The string is: %s \n", str);
/* error is still present here */
printf("The reverse string is : %s", strrev(str));
return 0;
}
The above should answer your question although strrev() is currently causing an error!
Here is a link to a previous stackOverflow question on successfully reversing a string: Reversing a string in C

Where does the newline character come from in C?

I have the following program that takes as input the batsman names and their scores and prints the batsman with the highest score. I have written the following algorithm and it works. But the only problem I am facing is that, the newline character is getting displayed on the screen after the input has been gotten from the user.
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
int main()
{
int n;
char bat[100],maxs[100];
int score,max=INT_MIN;
scanf("%d",&n);
while(n--)
{
scanf("%99[^,],%d",bat,&score);
if(score>max)
{
max=score;
strcpy(maxs, bat);
}
}
printf("%s",maxs);
}
I have no clue of where the newline is coming from? Please see the output shown below. Any help is appreciated.
Imagine the following program:
#include <stdio.h>
int main() {
int a;
scanf("%d", &a);
char string[100];
scanf("%99[^,]", string);
printf("-----\n");
printf("%s", string);
}
Now execution could look like:
10 # %d scans 10 and leaves the newline in input
string, # then %99[^,] reads from the newline including it up until a ,
-----
string
How can I resolve this so that the newline is removed?
Read the newline. A space character in scanf ignores all whitespace charactesrs.
scanf(" %99[^,]", string);
You could ignore a single newline character, if you want to be "exact":
scanf("%*1[\n]%99[^,]", string);
You're getting a newline there because scanf() requires you to hit enter to proceed. This enter then gets stored in the string as well. You could remove newlines at the end or beginning with something like this (source here):
void remove_newline_ch(char *line)
{
int new_line = strlen(line) -1;
if (line[new_line] == '\n')
line[new_line] = '\0';
}

Why gets(sen) is not working in this code?

#include <stdio.h>
#include <string.h>
int main() {
char a;
char s[100];
char sen[100];
scanf("%c",&a); // take character
printf("%c",a); //print character
scanf("%s",s); //take input as a word
printf("\n%s",s); //print the word
if((gets(sen))=='\n')
gets(sen);// take input as a string
puts(sen); //print that string
}
As gets() takes input from buffer so it will take '\n' as input after that another gets() command should work but that is not working. It doesn't take any input. Why?
gets(sen) returns sen, which is the address of the char array.
Therefore, what you are trying to do should be
if(strcmp(gets(sen), "\n") == 0)
gets(sen);// take input as a string
However, this is error-prone because sen can be a space with a newline, which is not "\n" or so.

strtok gives empty string or something I don't know

I have the following source-code:
#include <stdio.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[])
{
char string[100];
printf("Give me some text. \n");
fgets(string, 100, stdin);
char delimiter[]=" ";
char *erg;
erg=strtok(string, delimiter);
while(erg != NULL){
printf("Wort: %s \n", erg);
erg=strtok(NULL, delimiter);
}
return 0;
}
When I for example put in the text "abc def", the program is working like I want it to work. It print out the words "abc" and "def".
But when I put in the text "abc def ", it prints out "abc", "def" and "".
I don't want to print out the last empty "".
Can someone please tell me how to filter that ?
Gruß, Andre
IMO, you need to get rid of the last \n read by fgets() in fgets(string, 100, stdin);
You can do this in many ways, like
include the \n in your delimiter list. " \n", for example.
manually check the length of string, and at the last position, replace the \n with a \0.
fgets gets a whole string along with the \n character which you press after entering the string.So use
string[strlen(string)-1]='\0';
to replace the \n in string with a \0.

How to copy a sentence into a char array

I am trying to copy a sentence into a char array. I have tried using scanf("%[^\n]) and scanf("%[^\n]\n within an if statement but it doesn't work. Can someone please help me figure it out? I am using C language. It works with the first code but not the second.
File #1
#include <stdio.h>
int main ()
{
char c[10];
printf ("Enter text.\n");
scanf("%[^\n]", c);
printf ("text:%s", c);
return 0;
}
File #2
#include <stdio.h>
#include <string.h>
int main(void)
{
char command[10];
char c[10];
printf("cmd> ");
scanf( "%s", command);
if (strcmp(command, "new")==0)
{
printf ("Enter text:\n");
scanf("%[^\n]", c);
printf ("text:%s\n", c);
}
return 0;
}
Put a space before %[^\n] like so:
#include <stdio.h>
#include <string.h>
int main(void)
{
char command[10];
char c[10];
printf("cmd> ");
scanf( "%s", command);
if (strcmp(command, "new")==0)
{
printf ("Enter text:");
scanf(" %[^\n]", c); // note the space
printf ("text:%s", c);
}
return 0;
}
It should work now. The space makes it consume any whitespace of the previous inputs.
Here's my output when I tested it without the space:
cmd> new
Enter text:text:#
------------------
(program exited with code: 0)
And with the space:
cmd> new
Enter text:test
text:test
------------------
(program exited with code: 0)
According to the man page of scanf function, the usual skip of leading white space is suppressed if you use the [ character in the format string. So in the first case, it accepts all the characters until it meets the \n character; In the second case, after the first call of scanf function, the \n character (you press the Enter key in the first call) is still in the input buffer, so if you uses the format string "%[^\n]" in the scanf function, it reads an empty string into the buffer (As already mentioned, it skips the white space in this format case). So you can use the format string " %[^\n]" to force the scanf function to skip the white space.

Resources