Issues with scanf reading input too soon? - c

My problem is as follow: I need scanf to read multiple lines of user input. The user can input any combination of characters separated by whitespace or newline characters. My objective is to take each input that is separated by whitspace or newlines, and process it and output via printf. However, I am not allowed to store multiple inputs at once. My issues is this: every time the user presses enter, the scanf reads the entire line since I have scanf in a while loop != EOF. However, I don't want the scanf to read all lines of input until the user presses EOF. Is this possible? Here are some examples below:
Some pseudo code:
User Input:
cat dog mouse rabbit
snake dog
pink bob
joke*/
//Some pseudo code:
char input[100];
while (scanf("%s", input) != EOF) {
printf("%s", input);
}
In summary, I don't want scanf to read when the user presses enter since if it does, then the printf will activate but still allow the user to input stuff in.
Is there a way to bypass this? Note: I have to use scanf and I can't store multiple separate inputs (like dog or cat) in a single array.
Thank you.

Just use a 2-dimensional array, where each row stores a line of the input string. And as for accepting the input, ask the user to enter the number of lines which he/she would be giving and just loop through it.
#include<stdio.h>
void main(){
char inp[10][50];
int i,j,n;
printf("\nenter the number of lines: ");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf(" %[^\n]s",inp[i]);
}
//for printing it out.. follow the same with printf
printf("\nthe strings are:\n");
for(i=0;i<n;i++){
printf("%s\n",inp[i]);
}
}

Related

C while loop does not stop running once input is made

I am trying to create a program that repeatedly asks the user for input. However, in this case, the program just keeps printing "Enter your input" until it crashes after I enter something for the first time.
#include <stdio.h>
int main() {
while (1) {
char input[100];
printf("Enter a input: ");
scanf("%[^\n]s", input);
}
}
In:
scanf("%[^\n]s", input);
There are 2 problems:
The s is not part of that specific specifier, it should be only %[^\n].
That specifier leaves the \n newline character in the input buffer.
Your cycle will enter an infinite loop because there is always something to read there, but it's something that must not be parsed and should remain in the buffer.
A simple way to get rid of it is to place a space before the specifier:
scanf(" %[^\n]", input);
^
|
You are asking scanf() to read everything up to, but not including, the line break that ends the user's input.
So, the line break stays in the input buffer. Then on subsequent calls to scanf(), the line break is still not read from the input buffer, preventing scanf() from reading any new input.
You need to read that line break from the input buffer so that a subsequent call to scanf() can read the user's next input.

How to switch scanf input to standard terminal input after reading input through input redirection

I need to have my program read several words from a .txt file and store them into an array using the scanf() function. However, I need to accept user input after that also using scanf. How do I ensure that scanf only accepts user input after all the words are read?
I have tried using scanf() and getchar() to accept whitespace at the end of the file in case that is what scanf is reading at the point where I need user input.
char w[15][100];
for(int i =0;i<15;i++)
{
if(scanf("%s", &w[i][0])=1)
{
scanf("%s", &w[i][0]);
}
getchar();
printf("Word read\n");
}
bool validAnswer2=false;
while(validAnswer2==false)
{
printf("Would you like to play again?\nType \"y\" to play again or \"n\" to exit: ");
scanf(" %c", &reply);
getchar();
if(reply=='y')
{
validAnswer2=true;
}
else if(reply=='n')
{
validAnswer2=true;
}
}
When the program reaches the point where scanf needs to accepts user input rather than file input, I have designed it to check if the input is a letter and try scanf again if it is not. The program infinitely tries scanf, each time getting invalid input. I am redirecting input by using nameOfFile < words.txt where words.txt is a file with 15 words.

What is wrong with my for loop? It turns 2 times when I enter only 1 input in a letter guessing game in C

I know this code is not completed yet, but I cannot go any further because of this issue.
If you execute the code with any compiler you will see it.
After the instructions gets written at console, when you enter a word, loop takes 2 turns. It reduces chance 2 times too when it's supposed to be 1. Why is that?
I am using devc++ and windows.
#include<stdio.h>
#include<stdlib.h>
int main(){
int i,j,totalTrial=6,currentTrial=0;
char myWord [6]={'d','o','c','t','o','r'};
char lineArray [6]={'-','-','-','-','-','-'};
char guess;
printf("Hello,this is a simple word-guessing game. Try to find my secret word. You have 6 chances.");
printf("Lets begin!!\n");
printf("Word:\n------\n");
for(i=0;i<=6;i++)
{
printf("\nGuess a letter: ");
scanf("%c",&guess);
for(j=0;j<7;j++)
{
if(guess==myWord[j])
{
lineArray[j]=guess;
}
}
currentTrial++;
printf("\nResult: %s, %d hakkin kaldi.\n",lineArray,totalTrial-currentTrial);
}
getch();
return 0;
}
This is happening because the scanf() is reading the stray \n (newline character) from the input buffer. [When you are giving input, you must be entering a character followed by ENTER key.]
To resolve this, add a space before % character in scanf() like this:
scanf(" %c", &guess);
This will skip the leading whitespace characters (including newline character) and read the input given by the user.
With regard to the line:
scanf("%c",&guess);
How many characters do you think are turning up when you enter, for example, dENTER? I'll give you a hint, it isn't one :-)
The problem is that your scanf will read each character in turn and process it, including the newline generated when you hit ENTER.
A better solution would be to use a more complete input solution such as this one here.
It will handle many scenarios that a simple method based on scanf or getchar.

Scanning text forces me to go in next line, to confirm input. Can I prevent this for a special case?

So basically I have a a program in C, whose point is to look organized.
I'd like my program's cursor not to move after I confirm my Scanf statement.
Heres example part of my program and its output:
#include <stdio.h>
int main()
{
char input[10];
int voltage=220;
printf("What do you want to know\n"); //no need to correct me on this part please
scanf("%s", input);
if (strcmp("voltage",input)==0)
printf(" = %d\n", voltage);
/* Imagine other string comparisons (resistance, current) here*/
return 0;
}
So this program for input "voltage" would output something like this:
voltage //what I just inputed via scanf
= 220 // \n because I pressed enter after inputing.
What I wanted is:
voltage = 220
I dont know Is there reverse \n function that I dont know about.
There is no standard way in C to read input without pressing Enter. You will have to go for platform specific functions.
There are lots of questions here in StackOverflow that cover this, such as Capture characters from standard input without waiting for enter to be pressed

fgets printing two lines before input

So I am trying to write a program that will let me read a user input for data on an MP3 file using a doubly linked list data structure. I got most of the methods and functions to work, but when I am prompting the user to put in input it prints out two lines before the user can input for the first line. So for example
int main()
{
int user_input = 0;
while(!(user_input >= 4))
{
struct MP3_data_node* MP3_data;
MP3_data = (struct MP3_data_node*)malloc(sizeof(struct MP3_data_node));
printf("\nPlease select a number for one of the following instructions:\n");
printf("0: add to list\n1: delete from list\n2: print the list from beginning to end\n3: print the list from end to beginning\n4: exit\n");
scanf("%d", &user_input);
if(user_input == 0)
{
printf("Please provide the artist:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the album:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the song title:");
fgets(MP3_data->artist,50,stdin);
printf("Please provide the year the song was released: ");
scanf("%d", &MP3_data->yearReleased);
printf("Please provide the length of the song in seconds: ");
scanf("%d", &MP3_data->runTime);
addToList(MP3_data);
}
...
So it prints out "Please provide the artist:Please provide the album:" and then let's me put the input in, so my question is how do I make it so that it prints:
Please provide the artist: (user input)
Please provide the album: (user input)
etc.
You're doing the right thing (fgets) int the first few prompts, then you switch to scanf which is the source of your problem. Use fgets (and strtol) instead of scanf and you will be fine. (And, the first scanf which causes the problem described in your question.)
The problem is that scanf only reads the digit part of whatever you enter. That means if you type 12Enter, then the scanf reads the 1 and 2 but leaves the Enter in the input buffer for the next call to fgets or scanf. On the other hand, fgets reads everything you type including the Enter, avoiding this problem.

Resources