I have two problems with the code, the first one being that the program wants me to enter my number twice and the second one being that the program closes down immediately after it has finished its process.
I have tried to use the getchar() statement to stop it doing so but it doesn't seem to work.
#include <stdio.h>
int square(int); /*function prototype*/
main()
{
int x; /*defining the function*/
printf("Enter your number\n");
scanf_s("%d \n", &x); /*reading the users input*/
printf("Your new answer is %d \n", square(x)); /*calling the function*/
getchar();
getchar();
}
int square(y) /*actual function*/
{
return y * y;
}
Fix the issue by changing
scanf_s("%d \n", &x);
to
scanf_s("%d", &x);
The problem was that a whitespace character (space, newline etc) in the format string of scanf insructs scanf to scan and discard any number of whitespace characters, if any, until the first non-whitespace character.
As for the problem with getchar(), replace the first getchar() with:
int c;
while((c = getchar()) != '\n' && c != EOF);
This will scan and discard everything until a \n or EOF.
Also, change
main()
to
int main(void)
and
int square(y)
to
int square(int y)
I would recommend using scanf("%d", &x); to read your number. Your problem is that your argument looks like this:"%d \n" so the program expects you to enter your number AND \n. This way, you say how you want your x to look, and in your case, it expects it to be a numeric value, a space and end of line.
As for the closing one, use getch();. For this function, you need to include the conio.h like you did with stdio, meaningly: #include <conio.h>.
Related
I'm writing a program that asks the number of strings which i'll then count how many spaces it has.
My problem is when I start a new cycle I can't allocate the array of characters I use to count the spaces.
Thanks in advance.
#include <stdio.h>
#include <string.h>
int main(){
char a[20];
int x, z, esp=0, num;
scanf("%d\n", &num);
int array[num];
for (int i=0;i<num;i++){
scanf("%[^\n]", &a);
z =strlen(a);
for (x=0; x<=z; x++){
if (a[x] == ' '){
esp++;
}
}
array[i] = esp;
esp =0;
}
for (int i=0;i<num;i++){
printf ("%d\n", array[i]);
}
return 0;
}
Problems:
Not having all warnings enabled. Save time, enable them all.
'\n' blocks for more input in scanf("%d\n", &num);
Not checking scanf() return value.
Not limiting input with a width in scanf("%[^\n]", &a);
Wrong type passed in scanf("%[^\n]", &a);
Big one: not consuming the end-of-line with repeated scanf("%[^\n]", &a); calls.
Perhaps more.
Repaired code:
// scanf("%d\n", &num);
if (scanf("%d", &num) != 1) { // '\n' removed
puts("Error1");
return -1;
}
// scanf("%[^\n]", &a);
if (scanf(" %19[^\n]", a) != 1) { // ' ' consumes white-space like \n
puts("Error2");
return -1;
}
On the first scanf, remove \n character, after the first scanf, add getchar() to consume new line character.
Replace second scanf with gets;
Then it will work correctly.
By the way, since gets is unsafe, you can use fgets with stdin parameter and max character count parameter instead of gets.
Thanks to everyone who commented and answered my question, I think I wasn't able to explain myself properly. It's a code which reads a number, the number of the lines of characters which then it'll count the spaces of; my problem started when the code executes a new cycle in which this scanf didn't let me enter the string of characters again: scanf("%[^\n]", &a), but did everything else in the cycle while using the same string.
I'm really new to this, coding and the page itself so thanks for the advices. I was able to find a solution: scanf("%[^\n]%*c, &a)
%*[^\n] scans everything until a \n, but doesn't scan in the \n. The asterisk(*) tells it to discard whatever was scanned.
%*c scans a single character, which will be the \n left over by %*[^\n] in this case. The asterisk instructs scanf to discard the scanned character.
And here is the updated code:
#include <stdio.h>
#include <string.h>
int main(){
char a[20];
int x, z, esp=0, num;
scanf("%d\n", &num);
int array[num];
for (int i=0;i<num;i++){
scanf("%[^\n]%*c", &a);
z =strlen(a);
for (x=0; x<=z; x++){
if (a[x] == ' '){
esp++;
}
}
array[i] = esp;
esp =0;
}
for (int i=0;i<num;i++){
printf ("%d\n", array[i]);
}
return 0;
}
I'm new to C and I need help with this simple exercise using for. I need to get a char and an int value from the user. Then I have to print that char as many times as the int entered before.
This is what I have:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a;
printf("Enter a character:");
scanf(" %c", &a);
int n;
printf("Enter a number:");
scanf(" %c", &n);
printf("\n");
int x;
for(x=0; x < n; x++){
printf(" %c", a);
}
return 0;
}
My problem is that it makes an infinite loop in the for.
Please I need your help.
Thanks
Here, n is an int, not a char. Thus, you need to use %d to read it. Using %c here will cause undefined behavior. According to "C99 – ISO 9899-1999":
§7.19.6.2 The fscanf function1
[...] If this object does not have an appropriate type, or if the result of the conversion cannot be represented in the object, the behavior is undefined.
Change
scanf(" %c", &n);
to
scanf(" %d", &n);
Check out here for more info.
1: The scanf function is equivalent to fscanf with the argument stdin interposed
before the arguments to scanf.
So here is my program. It is suposed to write out square of some intiger.
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.");
scanf("%i", &a);
printf("Square of that intiger is %i", a*a);
return 0;
}
When i run a program in Eclipse it first requires me to input a number.I put in 5. And then as output it gives me
Type an intiger.Square of that intiger is 25.
It should first print "Type an intiger" and then the rest. But it just combines two printf commands. What is the problem?
You need a newline character - printf("Type an intiger.\n");
In computing, a newline, also known as a line break or end-of-line
(EOL) marker, or simply break, is a special character or sequence of
characters signifying the end of a line of text.
Also format specifier for integer is %d
scanf("%d", &a);
printf("Square of that intiger is %d", a*a);
If you want it on separate lines you can always add '\n' to the string to get a new line.
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.\n");
scanf("%i", &a);
printf("Square of that intiger is %i", a*a);
return 0;
}
There is 2 problem in it. First, if you input the integer, it should be %d. Example :
scanf("%d", &a);
The second, after the input, you should print \n. So, it will be like this printf("\n");. Take a look at my code :
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.");
scanf("%d", &a);
printf("\nSquare of that intiger is %d", a*a);
return 0;
}
In code::blocks it compiles fine anyway put a \n at the end of the first printf and change %i with %d
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.
#include <stdio.h>
int main (void)
{
int T, y, z;
scanf ("%i\n", &T);
for (T; T > 0 ; --T)
{
scanf ("%i\n", &y);
}
return 0;
}
If I input 4, shouldn't it take 4 more inputs? Instead it allows me to enter 5 integers! Tried it for other numbers too.
The format string in scanf works as follows (see http://www.cplusplus.com/reference/cstdio/scanf/)
[The format is a] C string that contains a sequence of characters that control how
characters extracted from the stream are treated:
Whitespace
character: the function will read and ignore any whitespace characters
encountered before the next non-whitespace character ...
In both your scanf() you have a newline. Therefore the first time you hit the enter key, it is ignored by scanf.
Some of the answers are telling you to modify the loop... this is incorrect, your loop is fine. it is the above that's causing you the headache. Try the following:
#include <stdio.h>
int main(int argc, char const *argv[])
{
int T, y, z;
scanf ("%i", &T);
printf("Count is= %d\n", T);
for (T; T > 0 ; --T)
{
printf("T= %d\n", T);
scanf ("%i", &y);
}
return 0;
}
EDIT: Thank you to Daniel Fischer for his comment about flushing stdin, which I have now removed. Found this explanation (Using fflush(stdin)).
Just get rid of \n from your scanf