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';
}
Related
#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.
I have a typical question it's not that how can I scan spaces using scanf but how to scan the initial spaces entered in a string
This is what I've done:
#include <stdio.h>
#include <string.h>
int main()
{
int n;
char a[10];
scanf("%d",&n);
scanf(" %[^\n]",a);
printf("%d",strlen(a));
return 0;
}
and when I run the program with following input:
aa bb//note there are two spaces before initial a
and the output is 6 but there are 8 characters i.e, 2 spaces followed by 2 a's followed by 2 spaces and then lastly 2 b's
I eve tried an own function.. but alas! the length is 6. Here's my function:
int len(char a[101])
{
int i;
for(i=0;a[i];i++);
return i;
}
What I think is that the initial 2 spaces are being ignored...or I might be wrong. It'd be great if someone could explain why the length of string is 6 and how can I make it 8 or accept all the 8 characters I mentioned above.
EDIT: this is my actual code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,N,j,k;
char **ans,s[101];
scanf("%d",&N);
ans=(char **)calloc(N,sizeof(char*));
for(j=0,i=0;i<N;i++)
{
scanf(" %[^\n]",s);
printf("%d",strlen(s));
ans[i]=(char*)calloc(strlen(s),sizeof(char));
for(k=0,j=((strlen(s)/2)-1);j>=0;j--,k++)
{
ans[i][k]=s[j];
}
for(j=strlen(s)-1;j>=strlen(s)/2;k++,j--)
{
ans[i][k]=s[j];
}
}
for(i=0;i<N;i++)
{
printf("%s\n",ans[i]);
}
scanf("%d",&i);
return 0;
}
OP code should work as posted.
OP comments true code is using scanf(" %[^\n]",a); which fully explains the problem: the space in the format is consuming leading white-space.
To address other issues with scanf(), see following.
fgets() is the right tool.
Yet if OP insists on scanf()
how can I scan spaces using scanf but how to scan the initial spaces entered in a string?
char buf[100];
// Scan up to 99 non\n characters and form a string in `buf`
switch (scanf("%99[^\n]", buf)) {
case 0: buf[0] = '\0'; break; // line begins with `'\n`
// May want to check if strlen(buf)==99 to detect a long line
case 1: break; // Success.
case EOF: buf[0] = '\0'; break; // stdin is closed.
}
fgetc(stdin); // throw away the \n still in stdin.
The issue i believe is that you need to be getting length from a Pointer to the array not the array itself.
Try this, this code worked for me.
int ArrayLength(char* stringArray)
{
return strlen(stringArray);
}
scanf("%d",&T);
printf("%d",T);
for(i=0;i<T;i++)
{
scanf("%450[^\n]",str2);
printf("%s",str2);
}
I am trying read the following using file redirection on the gcc compiler
3 // number of lines to read
// line 1 intentionally left blank(pressed enter)
hello world // line 2 to read
hello world2 // line 3 to read
But iam getting the following output
3
// blank
// blank
// blank
I have already read the previous posts on stack overflow on the usage of various varieties of scanf to read line by line.But none seems to work in my case.Where I went wrong?
If you want to read a line simply use fgets().
fgets(str2, length, stdin);
The complete example would be:
#include <stdio.h>
#include <stdlib.h>
int main(){
int T, i;
char str2[1024];
fgets(str2, 1024, stdin);
sscanf(str2, "%d", &T);
printf("%d\n",T);
for(i=0;i<T;i++)
{
fgets(str2, 1024, stdin);
printf("%s", str2);
}
return EXIT_SUCCESS;
}
Of course if you can't rely on the input being valid you could also add some checks verifying the return value of fgets, and maybe use strtol instead of sscanf.
The line
scanf("%450[^\n]",str2);
leaves the newline character in the input stream. Add a line to read a character and discard it.
for(i=0;i<T;i++)
{
scanf("%450[^\n]",str2);
fgetc(stdin);
printf("%s\n",str2); // Add a newline to printf
}
Update, in response to comment by OP
There's newline character left on the input stream after scanf("%d",&T);. Add a line to read and discard that newline character too.
Updated function that works for me.
int main()
{
int T;
char str2[450] = {0};
int i;
scanf("%d",&T);
// Discard everything after the number
scanf("%*[^\n]"); // Discard all but the newline
fgetc(stdin); // Discard the newline
printf("%d\n",T);
for(i=0;i<T;i++)
{
scanf("%450[^\n]",str2);
fgetc(stdin);
printf("%s\n",str2);
}
return 0;
}
To solve your problem you need just to add a newline \n in the second scanf
scanf("\n%450[^\n]",str2); // note the \n before the % character
Morever, you need to add some newlines inside the function printf to get a good and readable output.
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.
I have program that asks to enter a string (mystring) and a char (ch). Then it deletes all entered chars (ch) from the string (mystring). For example "abcabc" and char 'a' then the result shoud be "bcbc".
-When I use scanf the program works nicely if the string does not have spaces. If I enter "abc abc abc" It reads and processes only the first 3 letters (until space).
Then I was advised to use gets(mystr); because it can read all the stirng. But when I use gets the result is the same as the input string and nothing happens.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
//gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
scanf("%c",&ch);
scanf("%c",&ch);
That second scanf is your problem. It's picking up the new-line character that you enter after the letter you want to remove (and overwrites the previous value of ch).
Get rid of it.
Please note, as the man page says:
Never use gets(). Because it is impossible to tell without knowing the data in advance how many
characters gets() will read, and because gets() will continue to store characters past the end of
the buffer, it is extremely dangerous to use. It has been used to break computer security. Use
fgets() instead.
hmm - not sure what the problem is - use getstr, but not scanf for the string, and it works for me in visual studio
int main(int argc, char *argv[])
{
char mystr[N] ,result[N];
char ch;
int i,k;
k=0;
printf("enter string \n");
gets(mystr);///////////////////////////
//scanf("%s",&mystr);///////////////////
printf("enter char \n");
scanf("%c",&ch);
// scanf("%c",&ch);
for ( i = 0; i <= strlen(mystr); i++ )
{
if (mystr[i] != ch)
{
result[k]=mystr[i];
k++;
}
}
puts(result);
system("pause");
return 0;
}
Use this one:
char temp[2];
scanf("%1s",temp);
ch = temp[0];
and use gets
scanf when used with chars has some problems (it gets the "old" new line). Here we "cheat" a little and we use scanf to get a string that can have up to one character. A string of 1 character clearly needs a second character for the terminator, so an array of 2 characters.
Be aware that using a scanf for the character to search, you won't be able to insert the space character.
Note that gets is an "evil" function. You can easily do buffer overruns using it (it doesn't check that the buffer is big enough). The "right" way to do it is normally: fgets(mystr, N, stdin); (the "file" variant of gets has a maximum number of characters that can be read and will append a \0 at the end). Note that if you insert 150 characters in a fgets, 99 will go to your string (because you gave 100 of max size), 1x \0 will be appended and the other characters will remain in the buffer "ready" for the next scanf/gets/fgets... (to test it, reduce the buffer to a smaller value, like 5 characters, and do some tests)
You can use fgets() as suggested by xanatos with a small hack, so you can reliably handle return characters. Just change the '\n' to '\0' in the string obtained using fgets.
And in your program, you forgot to terminate the new string with a '\0'.
So here's the code you're looking for.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int main(int argc,char **argv){
char string[N],str1[N];
char ch;
int i,k = 0;
fgets(string,N,stdin);
string[strlen(string)-1] = '\0';
scanf("%c",&ch);
printf("\n%s , %c",string,ch);
for (i=0;i<=strlen(string);i++)
if(string[i] != ch)
str1[k++] = string[i];
str1[k] = '\0';
printf("\n%s , %s\n",string,str1);
return 0;
}