I'm making a program in which i need to ignore not alphabetical characters when reading input.
for(i = 0; i < size; i++){
scanf(" %[A-Za-z]%*[^A-Za-z]s", A[i]);
}
The problem is, it asks for input twice exclusively in the first pass of the loop (i = 0), in a way that the last input (i = size-1) is ignored, but still asked for. The repeated input takes the second place in the array.
Related
I'm new to programming but I wanted to make a program that gets as input a number, (length) and then stores a series of a's and b's of said length. Finally it should output the numbers as the ascii numbers. (so 97 and 98)
I thought I should malloc a char array of the size length and then do a for-loop over it and print everything as an integer.
The problem is however that I get a value 10 as the value of the first letter.
Thanks a lot for any help!
int main()
{
int length;
scanf("%d", &length);
char *matrix = malloc((length + 1 ) * sizeof(char));
for (int i = 0; i < length; i++)
{
scanf("%c", &matrix[i]);
}
for (int i = 0; i < length; i++)
{
printf("\n%d", matrix[i]);
}
return 0;
}
When inputting 3 on the first line and aba on the next line, I get 10 97 98.
However I expected it to be 97 98 97. Why do I get a value of 10 in the first place of the array?
Use
scanf(" %c", &matrix[i]);
^^^^
instead of
scanf("%c", &matrix[i]);
^^
When the format starts with a blank all white spaces are skipped.
From the C Standard (7.21.6.2 The fscanf function)
5 A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read.
10 is the ASCII code of the (white space) new line character '\n' that was present in the input buffer after you entered the length of the array.
The first scanf() with the format string %d leaves a newline in the input buffer.
What happens here, is that your terminal collects input one full line at a time, passing it to the program, and then the scanf() only reads the digits from the buffer, leaving the newline character there for the next scanf() to see. The same would happen if you entered 10 abc: the space, abc and the newline would be left there.
This mismatch is not something people usually expect, and it's one of the things that makes scanf() annoying. I would suggest using fgets() instead to first read a full line, matching what the terminal gives, and then parse the number from it with sscanf() or strtol() (or atoi()).
This cleans up the issue at the point where the first line is read, instead of passing it on to the next input function to handle. Otherwise all your input functions are tied together, if the next input would be for a whole line with possible white space, you'd need to know if you expect to clear a pre-existing newline or not. (You could also replace the later scanf("%c") with getchar(), not that that matters with buffering though.)
That said, the scanf("%c")/getchar() loop may still see newlines if you enter lines that don't have as many characters as the loop expects, so if you don't want to see them at all, filter them out.
So, something like this:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int length;
char linebuf[100];
fgets(linebuf, 100, stdin);
length = strtol(linebuf, NULL, 10);
char *matrix = malloc(length + 1);
for (int i = 0; i < length; i++)
{
matrix[i] = getchar();
}
for (int i = 0; i < length; i++)
{
printf("\n%d", matrix[i]);
}
printf("\n");
return 0;
}
(The obvious downside of fgets() is that you have to decide on a maximum length for the input line, allocate a buffer and call another function in addition to it.)
I have written a program which accepts a value from a user and then iterates over that value in a for loop. in for loop I accept numbers to be stored in the array.
My problem is for loop accepts one extra value than specified by user.
int main()
{
int i = 0;
int a;
int no_of_boxcars = 0;
double array[10];
double boxcart_wt = 0;
//printf("Enter the no of wagons");
scanf_s("%d", &no_of_boxcars); // no of boxcars
for (i = 0; i<=no_of_boxcars;++i)
{
printf("%d \t", i);
scanf_s("%lf ", &boxcart_wt); //weight in boxcar
array[i] = boxcart_wt;
}
}
if the user enters 3 it should accept 3 values if
for (i = 0; i<no_of_boxcars;++i)
{
//but here accepts 4 values
}
if the user enters 3 it should accept 4 values if
for (i = 0; i<=no_of_boxcars;++i)
{
//and here accepts 5 values
}
Indexes in C go from 0..n-1. In your for loop you go from 0..n and that is one too many. Change
for (i = 0; i<=no_of_boxcars;++i)
to
for (i = 0; i<no_of_boxcars;++i)
A space in the scanf format matches any white-space, and any number of consecutive white-space.
The problem with a trailing space is that then scanf must continue reading until it reads something that isn't a white-space, otherwise it doesn't know when the spaces ends.
That leads to the problem that you need to give some extra non white-space input.
For all but two formats ("%c" and "%[") the scanf function automatically reads and discards leading white-space. So it's usually not needed to include spaces in a format string. Except perhaps for those two formats that doesn't skip white-space.
Read e.g. this scanf (and family) reference for more details.
This is a simple program in which the user enters a series of numbers which are then added. The result is printed on the screen. Here's the code:
int main() {
int * numbers;
int result = 0;
int howMany;
int i;
printf("How many numbers would you like to add?\n");
scanf(" %d\n", &howMany);
numbers = (int *) malloc(howMany * sizeof(int));
for(i = 0; i < howMany; i++){
printf("Please enter number %d.\n", i + 1);
scanf(" %d\n", &numbers[i]);
result = result + numbers [i];
}
printf("Result: %d", result);
return 0;
}
But there is a problem. The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?
Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.
Thanks.
The program asks for how many numbers the user would like to add twice for some reason. Why is that? How can I fix it?
Your program prompts me only once for how many numbers. It does, however, defer asking for each specific number until after I enter it, and then it requires an extra non-blank line after the last (late) prompt before it outputs the result.
Also, not sure if this is related but the results also make no sense. Sometimes they are correct, other times they aren't, not sure why either.
It is related: the fact that the per-number prompts are late is confusing you about which numbers are being added.
This all comes down to your scanf() formats, as #Mark already remarked (albeit somewhat tersely). Any nonempty run of whitespace, including newlines, in a scanf() format matches a possibly-empty run of whitespace. When it is matching such a run, scanf() has to keep scanning until it sees a non-whitespace character. Interactive input is line-buffered, however, so no new input is available to it until you send a whole new line. Then the first non-whitespace character on that next line is ready and waiting for the following scanf().
scanf() can be quite tricky to use correctly, especially for interactive input. It is best suited for fixed-format input. You can do this with scanf() -- #Mark showed you how -- but the usual recommendation around here is to use fgets() to read input one line at a time, and sscanf() (or your choice of other mechanism) to parse each line. Even that can be a challenge to make bullet-proof, but you start out on firmer footing.
Your problem was because of your erroneous placement of the newline characters in your printf and scanf functions.
Here is the code you are probably looking for:
int main() {
int * numbers;
int result = 0;
int howMany;
int i;
printf("How many numbers would you like to add?: ");
scanf("%d", &howMany);
numbers = (int *) malloc(howMany * sizeof(int));
for(i = 0; i < howMany; i++){
printf("Please enter number %d: ", i + 1);
scanf("%d", &numbers[i]);
result = result + numbers [i];
}
printf("Result: %d\n", result);
return 0;
}
I want to use scanf_s("%c\n", &arr[index]) to input once character at a time in a single line using for/while loop. I cannot figure out how to output the result. Below is the code.(I only want to use scanf statement. fgets way is easy.
printf("\nEnter the lowercase letters\n");
for (index = 0; index < size; index++)
{
scanf_s("%c\n", &arr[index]);
_getch();
}
printf("\nThanks");
for (index = 0; index < size; ++index)
{
printf("%c/n", arr[index]);
}
It takes the input but exits out after thanks statement. I cannot figure out why. Although I have used a different method that works. It's just a variation I was trying.
Change
scanf_s("%c\n", &arr[index]);
_getch();
To
scanf_s(" %c", &arr[index], 1);
When scanning a character(%c) or string(%s) using scanf_s, you must supply an additional value as a parameter which indicates the amount of characters to be scanned.
The space before %c discards all whitespace characters(newlines, spaces etc) including none before scanning a non-whitespace character.
Also, the printf in the loop has /n instead of \n for a newline.
This code would probably work better:
int nchars;
printf("\nEnter the lowercase letters\n");
for (index = 0; index < size; index++)
{
if (scanf_s("%c", &arr[index], 1) != 1)
break;
}
printf("\nThanks\n");
nchars = index; // Do not report on values that were not entered
for (index = 0; index < nchars; ++index)
{
printf("%c\n", arr[index]);
}
Note that when you use scanf_s() and the %c format (and %s and %[…]formats), it require a length as well as the pointer to the data storage location (two arguments for one conversion specification). This tells the function how much space there is available to store the value. Often, the length will not be 1; you'd use scanf_s("%s", buffer, sizeof(buffer)) to read a string.
It is a good idea to check the return value from scanf_s() every time you use it so that you know whether it worked or not.
You can add extra criteria for breaking the loop, such as if the code reads a newline.
I also noted some problems in the comments — the issues are fixed in the code above.
Why are you using _getch() when you're also scanning with scanf_s()? That's going to confuse the poor user who types abcd and sees only ac. The _getch() is eating the b and d.
Also, newline is \n not /n — the third printf() has that as a typo.
Using \n at the end of an interactive input format string is a bad idea; the user has to type something that's not a white space character after the input to get the scanf_s() to return.
My program scans from input and prints all the capital letters used.
Im trying to print the original input from stdin at the end of my program too.
But when i use printf, it seems to skip the first part of the input expression, printing the remaining stuff in my character array. Please help me see where the problem lies. -comments in code-
#include <stdio.h>
int main(void){
char input[81];
int letters[91];
int i;
//initialize arrays input and letters
for (i = 0; i < 90; i++) letters[i] = 2;
for (i = 0 ; i < 80; i++) input[i] = 'a';
i = 0;
//reads into input array until EOF
while((scanf("%c",input)!= EOF)){
//checks input for characters A-Z
if((input[i]>= 'A' && input[i]<= 'Z'))
letters[input[i]] = 1;
}
//prints capital letters from input that occur at least once
for(i = 'A'; i < 'Z'; i++){
if (letters[i]==1)
printf("%c", i);} // this output works fine, the scan worked??
//print blank line
printf("\n\n");
// print input
printf("%s\n", input); //This is where the incorrect output comes from.
return 0;}
does my original input change? why?
did my input not get scanned correctly in the first place?
please respond quickly!
Here:
while((scanf("%c",input)!= EOF)){
you're only ever reading characters into input[0]. This is fine for what you're doing for letters, but obviously when you try to print out input, it's not going to work as you expect.
When you fix it, you'll also need to remember to add a terminating \0 after the last input character.
The scanf loop reads your input one character at a time, and stores that one character in input[0]. When the scanf loop is completely finished, input[0] contains the last character read, and the rest of input is untouched.
To repair, you need to include i++ at the end of the scanf loop.
By the way, it would be clearer (and more efficient) to fill the input buffer with a single call to fgets then loop through the input buffer with: for (i=0; buf[i]!='\0'; i++) { ... }
You must do
while((scanf("%c",&input[i])!= EOF))
{i++;}
instead of this
while((scanf("%c",&input)!= EOF))
{}
What you are doing is scan the character into the address of the first element int the array everytime, hence it gets overwritten again and again. Remaining part of the input[] array is not being accessed, and hence does not change