scanf whitespace inside a function - c programming - c

From previous threads, I know that you can achieve this by using the method shown here: How do you allow spaces to be entered using scanf?
It works in Main but when I put it inside a function, it doesn't work.
This is my code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void dataInput();
struct record {
char title[50];
char author[50];
char category[20];
float price;
};
struct record info[500];
void main(){
dataInput();
}
void dataInput(){
int x;
for(x = 0; x <= 10; x++ ){
scanf("%s", &info[x].title);
printf("%s\n", &info[x].title);
}
}
Output:
If I use regex:
scanf("%50[0-9a-zA-Z ]s", &info[x].title);
Output:
Hmm whats wrong here

I haven't got the most robust reference manual by hand, but from Wikipedia:
%s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length.
So %s does very different things in scanf and printf, and will in fact only read one word in scanf, whereas in printf it will yield the null terminated content pointed to.

Your problem is pretty much explained here:
http://www.cplusplus.com/reference/cstdio/scanf/
For the %s format you have this:
Any number of non-whitespace characters, stopping at the first
whitespace character found. A terminating null character is
automatically added at the end of the stored sequence.
That is why when you using a regex the problem disappears.

Try
scanf("%[^\n]", &info[x].title);

scanf (" %[^\n]%*c", &info[x].title);
Notice that there is a SPACE before %[, this will work correctly

Related

Scanf changing the input in C

I have a fairly basic problem but I can't manage to solve it.
I'm trying to get an input from a user like this :
int main() {
char coord[2];
fflush(stdin);
scanf("%c", coord);
}
When i'm trying this code with printf("%c", coord);, it displays a completely different string from what I typed. For example, if I type "g6", it prints "Ê". I really have no clue why it's happening.
Thanks for helping me !
If you want to get string(char array) from user you should do this :
scanf("%s",coord);
%c is for single char
First of all avoid using fflush (stdin);. Standard input flashing is undefined behavior, according to C standard, and may lead to big issues .
Then, you are trying to get an input string using %c format, that is supposed to acquire a single character. Furthermore, your coord array has not enough room for the string terminator character (\0).
The format to be used in order to acquire a string with scanf (and to print it with printf) is %s:
int main() {
char coord[3] = {0};
scanf("%2s", coord);
printf ("%s\n", coord);
}
The "2" added to the format makes sure that at most two characters are read (exactly those you can have in you string array without overwriting the last character).
For starters this statement
fflush(stdin);
has undefined behavior and shall be removed.
The conversion specifier %c of printf expects an argument of the type char while you are passing an expression of the type char * to which the array designator is implicitly converted
printf("%c", coord);
you have to write either
printf("%c", *coord);
or
printf("%c", coord[0]);
Pay attention to that using this call of scanf
scanf("%c", coord);
you can enter only a single character. You can not enter a string.
If you want to enter a string in the array coord that has only two elements then you have to write
scanf( "%1s", coord);
In this case the array will be filled with a string of length equal to 1.
In this case you can output it like
printf("%s", coord);
If you want to enter a string like this "g6" then you have to declare the array like
char coord[3];
and write the following call of scanf
scanf( "%2s", coord);
The line char coord[2]; declares coord as an array of characters (also known as a "string"). However, the %c (in both scanf and printf) reads/writes a single character.
For strings, you need to use the %s format.
Also, if you want to store/read/print the string, "g6", you will need to allocate (at least) three characters to your coord array, as you must terminate all C-strings with a nul character.
Furthermore, calling fflush on the stdin stream is not effective (actually, it causes undefined behaviour, so anything could happen) - see here: I am not able to flush stdin.
So, a 'quick fix' for your code would be something like this:
#include <stdio.h>
int main()
{
char coord[3]; // Allow space for nul-terminator
// fflush(stdin); // don't do it
scanf("%2s", coord); // The "2" limits input to 2 characters
printf("%s\n", coord);
return 0; // ALways good practice to return zero (success) from main
}

Print a middle character of a string

I must write a program in C that can print the middle letter of the string you entered. Spaces () are also calculated, and the number of characters must be odd.
Ex. Input
Hi sussie
--> 9 characters, including space
The output should be s.
I have tried this:
#include <stdio.h>
#include<string.h>
char x[100];
int main(void)
{
printf("Hello World\n");
scanf("%c\n",&x);
long int i = (strlen(x)-1)/2;
printf("the middle letter of the word is %c\n",x[i]);
return 0;
}
and the output always shows the first letter of the word I have entered.
You're only reading the first character from stdin (and incorrectly; you shouldn't be using &).
If you must use scanf, you should use this format:
scanf("%99[^\n]", x);
This is safe and doesn't read past the buffer.
Note that %s wouldn't work here. %s causes scanf to interpret whitespace as the end of the string.
A much better, safer, and easier solution would be to use fgets instead of scanf; fgets is safer and it doesn't require you to change a format string when you change the size of your array:
fgets(x, sizeof(x)-1, stdin);
This eliminates any possible issues with whitespace or buffer overflow.
int main()
{
char arr[1024];
char a;
int i,counter=0;
printf("enter string :: ");
fgets(arr,sizeof(arr),stdin);
for(i=0;i<strlen(arr);i++)
counter++;
for(i=0;i<strlen(arr);i++)
{
if(i==(counter/2))
printf("%c\n",arr[i]);
}
return 0;
}

How do I get the user to input a word for string comparison?

I'm running a while loop so the user can constantly enter expressions, until they indicate they want to quit the program. I'm using strcmp() to compare two strings so as soon as they enter quit the program will stop. But the program keeps going, any Ideas?
#include <stdio.h>
#include <string.h>
int main()
{
int min12=0;
char opper;
int x=0;
int min13;
char *Repeatprog="cont";
char *Repeatprog1="quit";
while (strcmp(Repeatprog,Repeatprog1))
{
printf("enter the integer number \n");
scanf( "%d %c %d", &min12, &opper, &min13);
printf("%d %c %d\n", min12, opper, min13);
printf("Type the word quit to end program\n");
scanf("%s", Repeatprog);
}
printf("Good Bye");
return 0;
}
Remember always that an Array is a Pointer to the first object of the array.
And secondly, in your call to scanf() you only read a character. Not a whole string (represented by %s in C)
So in conclusion, your call to scanf() shouldn't have a pointer and should have a string instead of a character.
scanf("%s", Repeatprog);
or simply
gets (Repeatprog);
EDIT :
As the commenter #EOF said, gets() is not a good idea since it can lead to Undefined Behaviour. That's because the program can read more characters than it should have and lead to overflow, thus it isn't secure.
So I recommend using char *fgets(char *str, int n, FILE *stream)
Note:
Also, your code is using string literals. So if you make any attempt to change the content of the char pointer then it will lead to Undefined Behaviour.
For this note, please thank the guys below me [comments]. I made a huge mistake and I'm sorry.

How to capitalize the first letter of each word in an array in C

I am trying to make a simple program that stores a user-input sentence in an array of at most 80 characters and then capitalizes each word of in the sentence. I think I'm on the right track, however when I run the program, only the first word of the sentence is displayed.
#include<stdio.h>
int main(void)
{
int i; /*indexing integer*/
char sen[81]; /*specify total of 80 elements*/
printf("Enter a sentence no longer than 80 characters: \n\n");
scanf("%s",sen);
if((sen[0]>='a') && (sen[0]<='z'))
{
sen[0]=(char)(sen[0]-32); /*-32 in ascii to capitalize*/
}
for(i=0;sen[i]!='\0';i++) /*loop until null character*/
{
if(sen[i]==' ') /*if space: next letter in capitalized*/
{
if((sen[i+1]>='a') && (sen[i+1]<='z'))
sen[i+1]=(char)(sen[i+1]-32);
}
}
printf("%s",sen);
return 0;
}
I have a feeling it is only printing the first word in the array because of the first if statement after the scanf, but I am not completely sure. Any help would be appreciated. Thanks.
By default, the %s conversion specifier causes scanf to stop at the first whitespace character. Therefore you could either use the %80[^\n] format or the fgets function.
#include <stdio.h>
scanf("%80[^\n]", sen);
Or:
#include <stdio.h>
fgets(sen, sizeof sen, stdin);
However, since scanf reads formatted data, human inputs are not suitable for such readings. So fgets should be better here.
I have a feeling it is only printing the first word in the array because of the first if statement after the scanf
No, that's because the %s specifier makes scanf() scan up to the first whitespace. If you want to get an entire line of text, use fgets():
char sen[81];
fgets(sen, sizeof(sen), stdin);
dont use scanf when you want to take multiple words as input: use either gets() or fgets()..
I run your code with gets() and puts() and it worked.

Reading multiple lines of input with scanf

Writing a program for class, restricted to only scanf method. Program receives can receive any number of lines as input. Trouble with receiving input of multiple lines with scanf.
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]",s)==1){
printf("%s",s);
}
return 0;
}
Example input:
Here is a line.
Here is another line.
This is the current output:
Here is a line.
I want my output to be identical to my input. Using scanf.
I think what you want is something like this (if you're really limited only to scanf):
#include <stdio.h>
int main(){
char s[100];
while(scanf("%[^\n]%*c",s)==1){
printf("%s\n",s);
}
return 0;
}
The %*c is basically going to suppress the last character of input.
From man scanf
An optional '*' assignment-suppression character:
scanf() reads input as directed by the conversion specification,
but discards the input. No corresponding pointer argument is
required, and this specification is not included in the count of
successful assignments returned by scanf().
[ Edit: removed misleading answer as per Chris Dodd's bashing :) ]
try this code and use tab key as delimeter
#include <stdio.h>
int main(){
char s[100];
scanf("%[^\t]",s);
printf("%s",s);
return 0;
}
I'll give you a hint.
You need to repeat the scanf operation until an "EOF" condition is reached.
The way that's usually done is with the
while (!feof(stdin)) {
}
construct.
Try this piece of code..
It works as desired on a GCC compiler with C99 standards..
#include<stdio.h>
int main()
{
int s[100];
printf("Enter multiple line strings\n");
scanf("%[^\r]s",s);
printf("Enterd String is\n");
printf("%s\n",s);
return 0;
}

Resources