How to use one print statement to output multiple lines of text - c

this is not a problem I was just wondering if I could use fewer print statements for this problem.
#include <stdio.h> // for print statments
int main(int argc, char const *argv[]) {
int thisNumber;
printf("%s", "Hey you! input your Number here: " );
scanf("%d", &thisNumber );
printf( "%s","Your number is: " );
printf("%d\n", thisNumber );
return 0;
}
I have tried this:
#include <stdio.h> // for print statments
int main(int argc, char const *argv[]) {
int thisNumber;
printf("%s", "Hey you! input your Number here: " );
scanf("%d", &thisNumber );
printf( "Your number is: %d", thisNumber );
return 0;
}
And the output was:
> Hey Bekhruz! input your Number here: <my input say:125>
> Your number is: 125%
and for some reason, I have a % sign at the end with this code. Why is it occurring and how can i solve it? Thanks!

That's your shell prompt. The problem is not the appearance of %; the problem is that it's on the same line as your program's output. This is solved by outputting a line feed.
printf( "Your number is: %d\n", thisNumber );
When you combined the two statements, you left out the \n.

Related

How do you ask the User multiple questions in C?

I am new to "C programming" and I have Googled for my answer, but I can't seem to get what I am looking for. I am making a simple 2 question program. The code is listed below:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char characterName[] = "Mike";
int age = 0;
printf("Enter your age, %s.\n", characterName);
scanf("%d", &age);
printf("Your being %d is old older than me and my brother "
"which was the first computer.Hahaaa.... \n", age);
return 0;
}
This is the next question:
char str[50];
{
printf("Anything to say about my comment? \n");
scanf ("%[^\n]", str);
printf("That was a good answer. I wasn't expecting that from you.\n");
return 0;
}
How about a function to ask a question, and return a response?
#include <stdio.h>
/*
* Prompt the user with the given question, return their
* input in answer, up to max_answer_length bytes
* returns 1 for ok, 0 on error.
*/
int askQuestion(const char *question, char *answer, const size_t max_answer_length)
{
int input_ok = 1;
// Show the user the question
printf( "%s: ", question );
// Throw away any existing input in the user's input-queue
// (like if they answered with a really-long string previously)
fflush(stdin);
// Read a line of input from the user into <answer>, but not more
// than <max_answer_length>-1 bytes are accepted (see fgets() for details)
// If the fgets() returns EOF or an error, make sure we remember it
if ( fgets( answer, max_answer_length, stdin ) == NULL )
input_ok = 0;
// return whether there was an error on input
return input_ok;
}
int main(void)
{
char answer_buffer[200];
askQuestion( "What is your favourite fruit?", answer_buffer, sizeof(answer_buffer) );
printf( ">> %s\n", answer_buffer );
askQuestion( "How long have you been programming C?", answer_buffer, sizeof(answer_buffer) );
printf( ">> %s\n", answer_buffer );
return 0;
}

Counting Number Of User Input in C Program

printf("Enter number of patients:");
int numberOfInputs = scanf("%d", &patients);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument d.\n");
}
I am asking the user to input one number as an argument, but would like to print out a statement if the user does not input anything or puts in more than one input. For example, once prompted with "Enter number of patients:", if the user hits enter without entering anything, I would like to print out a statement. The code above is what I have been specifically tinkering around with it for the past couple hours as a few previous posts on this site have suggested but when I run it in terminal, it does not work. Any suggestions? Thank you in advance, and all advice is greatly appreciated!
If I understand your question right, you want to print an error when the input is anything other than an integer and this includes newline as well. You can do that using a char array and the %[] specifier.
Example:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int patients;
char str[10];
printf("Enter number of patients:");
int numberOfInputs = scanf("%[0-9]", str);
if (numberOfInputs != 1) {
printf("ERROR: Wrong number of arguments. Please enter one argument.\n");
}
patients = atoi(str); //This is needed to convert the `str` back to an integer
}
This will print the error when the user just hits ENTER as well.
This looks super over-complicated, but it basically splits the input, checks it to be exactly one and than checks it to be an integer (and converts it). It works fine in loop as well and handles empty input.
I'm sure there are more elegant solutions to this problem, it's just a suggestion.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
int getNumberOfInput(char* str);
bool isNumber(char* str);
int main()
{
char str[512];
while(1)
{
printf("Enter text: ");
fgets(str, 512, stdin);
int numberOfInput = getNumberOfInput(str);
if ( numberOfInput == 0 )
printf("You must give an input\n");
else if ( numberOfInput > 1 )
printf("You have to give exactly one input\n");
else
{
if (!isNumber(str))
printf("The input is not an integer\n");
else
{
int input = atoi(str);
printf("input: %d\n", input);
}
}
}
return 0;
}
int getNumberOfInput(char* str)
{
char* word = strtok(str, " \t\n\v\f\r");
int counter = 0;
while(word != NULL)
{
++counter;
word = strtok(NULL, " \t\n\v\f\r");
}
return counter;
}
bool isNumber(char* str)
{
int i, len = strlen(str);
for (i=0; i<len; ++i)
if (!isdigit(str[i]))
return false;
return true;
}

c program not taking input properly and producding wrong output

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*-1;
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}
Input to the code is in the form:
t
n x
some_string_having_A_and_B
Sample:
1
3 10
ABA
expected output
-10
actual output
10
This code gives -10 if number of B is odd and 10 if number of B is even. I know the correct and optimal way of writing the program but I can't figure out, why this code is producing wrong ouput.
The first scanf("%c") reads the previous ENTER in the input stream.
Suggestion for fast fix: use a space inside the specification to have scanf ignore whitespace (Enter is whitespace).
Try
if (scanf(" %c", &st[j]) != 1) /* error */;
// ^ ignore whitespace
Suggestion for better fix: read all user input with fgets().
char line[100];
...
fgets(line, sizeof line, stdin);
if (sscanf(line, "%c", &st[j]) != 1) /* error */;
if(st[j]=='B')
x=x*-1;// you need to put bracket here.on -1
//correct form is x=x*(-1)
}
//corrected code starts from here
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int t,n,x,i,j;
char st[50];
scanf("%d",&t);
for(i=0;i<t;i++)
{
scanf("%d %d",&n,&x);
for(j=0;j<n;j++)
{
scanf("%c",&st[j]);
if(st[j]=='A')
x=x*1;
if(st[j]=='B')
x=x*(-1);// you need to put bracket here.on -1
}
printf("%d",x);
}
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
return 0;
}

C getting input from CMD

How do you get input using prompt? I tried compiling the code bellow into "a.exe" and executing it from CMD like "gcc a.exe 5", but it doesn't output the number like it was supposed to.
#include <stdio.h>
int main(int a)
{
printf("%d\n", a);
return 1;
}
Have I done anything wrong when installing the compiler or am I trying to run it wrong?
Your main() parameters are wrong, you should do it this way:
int main(int argc, char **argv) {
if(argc > 2) {
printf("%s\n", argv[2]);
}
else {
printf("No arguments\n");
}
}
Note that int argc represents the number of parameters and char **argv is an array containing all the parameters, as strings, including "gcc", "a.exe", etc.
In your case, if you run your program this way: gcc a.exe 5, your parameters would be: argc = 3, argv = ["gcc", "a.exe", "5"]
To get input using the prompt, the easiest way would simply be to use a scanf statement. scanf basically waits for, and scans user input, which can then be stored as a variable. For example, a code that would take input for "Give me a number." and then spits back the result would be:
#include <stdio.h>
int main()
{
int num; //Initializes variable
printf("Please give me a number.\n"); //Asks for input
scanf("%d", &num); //scanf is the function, %d reserves the space, and the &*variable* sets the input equal to the variable.
getchar(); //Waits for user to input.
printf("Your number was %d.\n", num); //Spits it back out.
return 0;
}
The output would be:
[PROGRAM BEGINS]
Please give me a number.
>>>5
Your number was 5.
[PROGRAM ENDS]
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc == 2)
printf("%d\n", atoi(argv[1]));
return 0;
}

C Language. Accept Alphabets only and seperate two questions?

I want the program to answer the first and last name separately while also accepting the input strictly to alphabets. Where do I find more info about that?? Thanks.
#include <stdio.h>
int main(void)
{
char MyFname[20];
char MyLname[20];
printf("Enter your first and last names: \n");
scanf(" %s %s", MyFname, MyLname);
printf("Goodbye %s %s, have a great day!", MyFname, MyLname);
return 0;
}
Edited to incorporate #chux's suggestions.
You can use character-classes in the conversion specification string.
#include <stdio.h>
int main() {
char alphabetic_string[80], numeric_string[80];
scanf(" %79[a-zA-Z] %79[0-9]", alphabetic_string, numeric_string);
return 0;
}
To ask two separate questions, uh, ask two separate questions!
#include <stdio.h>
int main() {
char ans1[80], ans2[80];
printf("Input answer to question 1: ");
fflush(NULL);
scanf(" %79[a-zA-Z]", ans1);
printf("Input answer to question 2: ");
fflush(NULL);
scanf(" %79[a-zA-Z]", ans2);
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main()
{
char buff[1024];
char MyFname[20];
char MyLname[20];
if ( fgets ( buff, sizeof buff, stdin ) != NULL )
{
if ( sscanf ( buff, "%[a-zA-Z] %[a-zA-Z]", MyFname, MyLname ) != 2 )
{
fprintf ( stderr, "Invalid input\n" );
exit ( EXIT_FAILURE );
}
}
printf ( "Goodbye %s have a great day!\nGoodbye %s have a great day!", MyFname,
MyLname );
return 0;
}
Enter your first and last names:
John smith
Goodbye John have a great day!
Goodbye smith have a great day!
It is best to use fgets to take input and then verifying with sscanf. sscanf will successfully return the total number of inputs read if format entered is correct.
Don't forget to leave space when entering first and last name i.e John smith

Resources