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;
}
Related
the assignment is to get an input string, and using no string library functions to be able to handle the string. this code at the moment doesn't even print out the string i get in. when I remove the functions from main it magically starts to print. any help would be greatly appreciated
#include <stdio.h>
#include <string.h>
#define SIZE 32
int isQuit(char str[]);
void isPalindrome(char str[]);
int main (){
int cont = 0;
char str[SIZE];
fflush(stdin);
printf("please enter a word:\n");
scanf("%s\n", str);
printf("%s\n", str);
while(cont == 0)
{
scanf("%s\n", str);
printf("%s\n", str);
cont = isQuit(str);
isPalindrome(str);
}
return 0;
}
You most likely are suffering from line buffering in your terminal. Until you write a newline character, any characters written are not displayed.
Try adding a newline when displaying your input:
printf("%s\n", str);
The same goes for any other printf calls you do that you want to ensure are displayed.
By the way, your null-termination test is incorrect. The escape character is \, not /. Change your loop to:
while (str[h] != '\0')
Or simply:
while (str[h])
There are a few things wrong with your code here:
while(isQuit(str) == 0)
{
isPalindrome(str);
return 0 ;
}
Since you have the return keyword in your loop body (unconditionally), the loop will execute at most one time.
Also, neither isQuit nor isPalindrome take input from the user. This means that even if you were to fix the loop by removing the return statement, it still wouldn't be right; you'd have an infinite loop of isQuit and isPalindrome being passed the same str that the user got asked for on line 15.
What you have to do is change your while loop to continually poll the user for input and act upon it, in addition to the issues pointed out in #paddy's answer.
#include <stdio.h>
int main(void) {
char str[100];
scanf("%s", str[0]);
printf("%c", str[1]);
return 0;
}
I am running this code. I have entered "Jagrit" as an input. I expect the output of above program is 'j'. But instead i get nothing as a output just a blank space. Can anyone tell me why is it so and what was the error in the code ?
scanf expects the address of memrory to write to read data to:
#include <stdio.h>
int main(void) {
char str[100];
scanf("%s", str);
printf("%c",str[0]);
return 0;
}
Have a look at the example section of this doc on scanf.
What was your intention with scanf("%s", "jargrit dolir") ?
This
scanf("%s","jagrit dolir");/*it doesn't put data into str, and doing that causes UB*/
So accessing str[0] may cause undefined behavior because str doesn't initialized & it's not having any data.
Instead use like below.
scanf("%s",str);/* now give input like jagrit dolir */
And then print str[0].
Edit :- since you modify the code. Have you read the manual page of scanf() ?
scanf("%s",str[0]);/* why you are not reading compiler warning here ?*/
Here %s expects argument of char* but you provided char type.
if you just want to take a input as a string can use fgets()
and just use str[0] to print the first character of the string
note that
printf() is used to print values only;
here is the simple version of the code:
#include <stdio.h>
# include<stdlib.h>
int main() {
char str[100];
fgets(str,100,stdin);
printf("%c",str[0]);
return 0;
}
when you use str[0] , you access it's value so the scanf should be like thit scanf("%s",&str[0]); or like this scanf("%s",str);
you also should expect the output to be 'a'
try this code
#include <stdio.h>
int main()
{
char str[100];
printf("%s","jagrit dolir");
printf("%c",str[0]);
return 0;
}
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.
I want to scan a line until newline is pressed. I'm aware of gets() function, but I wanted to learn it with scanf(). The problem is, that my program falls into an infinite loop, where it scans the input from user and then infinitely prints it out, where it should print once after each scan. Can anybody explain why is it behaving like this?
#include<stdio.h>
int main()
{
char str[100];
while(str[0]!='\0')
{
scanf("%[^\n]",str);
printf("%s\n",str);
}
}
If you insist on using scanf, then change format specifier:
" %[^\n]"
The space in front will skip any previous "dangling" \n
Also you should initialize the str array before checking the contents of it, better yet use a do-while-loop instead .
Something like this should work
char str[100] = {0};
do
{
scanf(" %[^\n]",str);
printf("%s\n",str);
}
while(str[0]!='q');
Personally I prefer to use fgets(...) in combination with sscanf(...)
Also it is good practice to check the return value of scanf, there is a return value for a purpose.
added another while condition, loops until "q" or "quit"
Since %[^\n] does not accept newline, input is not accepted in the second loop.
Probably, this will do what you want.
#include<stdio.h>
int main(void){
char str[100];
while(1== scanf("%99[^\n]%*c",str)){//%*c consumes newline. Also In case of only newline terminates the loop
printf("%s\n",str);
}
}
BLUEPIXY is absolutely correct. The first return from scanf() is leaving the \n in the input buffer. Subsequent scanf() calls will return right away without reading any characters from stdin because scanf() stops reading on a \n. So a loop ensues. One way to avoid the loop is to read the \n from the input after the call to scanf() as shown below:
#include <stdio.h>
int main()
{
char str[100] = {0};
do
{
scanf("%[^\n]",str);
getchar();
printf("%s\n",str);
}while( str[0] != '\0' );
}
You seem to be under some false beliefs regarding how input works. So I'm going to explain below.
You don't need to do this in a loop because scanf() doesn't read and return one character at a time when you specify a string format. The input is buffered by the terminal. When you ask scanf() to return a string, the terminal will only send the input string to scanf() when it a newline is received. When that happens scanf() returns the string without the newline.
You'll need to do extra work to turn off terminal line buffering. The below example code shows how to turn off terminal I/O buffering.
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
int main()
{
struct termios old_tio, new_tio;
unsigned char c;
/* get the terminal settings for stdin */
tcgetattr(STDIN_FILENO,&old_tio);
/* we want to keep the old setting to restore them a the end */
new_tio=old_tio;
/* disable canonical mode (buffered i/o) and local echo */
new_tio.c_lflag &=(~ICANON & ~ECHO);
/* set the new settings immediately */
tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);
do {
c=getchar();
printf("%c ",(char)c);
} while(c!='q');
/* restore the former settings */
tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);
return 0;
}
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