Issue with scanning char and printing it in C - c

(I am using VS community, that's the reason why i used "scanf_s")
I am trying to complete an assignment and i came across an issue that i couldn't solve no matter what i did. My code is =
char char_array[3];
inputchar_1D(char_array, 3);
outputchar_1D(char_array, 3);
And the functions are :
void inputchar_1D(char arr[], int size)
{
printf("\n\ninput : \n");
for (int i = 0; i < size; i++)
{
printf("\nEnter your character (%d) : ", (i));
scanf_s("%c", &arr[i]);
}
}
void outputchar_1D(char arr[], int size)
{
printf("output : \n");
for (int i = 0; i < size; i++)
{
printf("%c...\t", arr[i]);
}
}
output :
input :
Enter your character (0) :
Enter your character (1) : s
Enter your character (2) : output :
... s...
...
As you can see it is skipping the first scanf and going to 2nd one. There it asks me to write a character and once i do that it skips the 3rd one and goes to the 2nd function. Once there it prints my inputted 2nd character as the first one. The 2nd character is empty, and the 3rd character is for some reason this "╠" weird symbol.
QUESTIONS :
Why is it skipping the scanf
Why is my character input at arr[1] printed as the arr[0]
Why did it pass to the new line even though there is no \n
Thank you for sparing your time to help me with this...

Related

printing characters using array in c language?

I tried to scan and print the characters of array using below code but input characters are not matching with output characters
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
OUTPUT
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
Can anyone please clarify my doubt why is the output not matching with input
Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.
#include <stdio.h>
#include <string.h>
int main()
{
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
scanf("%s", s); /* In lieu of using a loop */
if (strlen(s) < n) /* Just in case less characters are entered than was noted */
n = strlen(s);
for (i = 0; i < n; i++)
{
printf("%c", s[i]);
}
printf("\n");
return 0;
}
The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.
:~/C_Programs/Console/InputOutput/bin/Release$ ./InputOutput
enter the value of n:
7
start entering the characters:
ABCDEFG
ABCDEFG
You might give that a try.
Regards.

Why is scanf(); skipping the first line?

So after scanf, the printf(); skips the first line
I have read some questions that tells that , "%[^\n]" must be " %[^\n]" to skip the newline.
I have tried it both, but it still print the same result and now I don't know why it doesn't work.
Example input
Enter number of Materi: 4
Materia 1 name : a
Materia 2 name : b
materia 3 name : c
materia 4 name : d
Output:
Materia - 1 : R╒fu
Materia - 2 : a
Materia - 3 : b
Materia - 4 : c
#include<stdio.h>
#include<windows.h>
int main(int argc, const char *argv[]){
int i;
int V;
printf("Enter number of Materi: ");
scanf("%d", &V); fflush(stdin);
//Insert materia
char materia[V][50];
for(i = 0; i < V; i++){
printf("Materia %d name : ", i+1);scanf("%[^\n]", &materia[i][50]);fflush(stdin);
}
for(i = 0; i < V; i++){
printf("Materia - %d: %s\n", i+1, materia[i]);
}
system("pause");
return 0;
}
There are several mistakes in the program
The array passed to scanf is wrong.
fflush(stdin) is non-standard, although Windows does support it it's not portable. But you aren't using Windows because it does not support the VLA char materia[V][50];
The newlines which the scanf format "%[^\n]" will stop at, are already the next character in the input buffer.
The return value from scanf was not checked. It is the number of items successfully scanned.
You can have buffer overflow because the input string length is not restricted.
Here is the adjusted code:
#include<stdio.h>
int main(int argc, const char *argv[]){
int i;
int V;
printf("Enter number of Materi: ");
if(scanf("%d", &V) != 1) {
/* add some error message */
return 1;
}
// fflush(stdin); // removed
//Insert materia
char materia[V][50];
for(i = 0; i < V; i++){
printf("Materia %d name : ", i+1);
// add a space to filter the newline
// correct the array passed
// and restrict the length to prevent buffer overflow
if(scanf(" %49[^\n]", materia[i]) != 1) {
/* add some error message */
return 1;
}
// fflush(stdin); // removed
}
for(i = 0; i < V; i++){
printf("Materia - %d: %s\n", i+1, materia[i]);
}
return 0;
}
About the newlines. Format specs %d and %s and %f automatically filter out leading whitespace, but %c and %[] and %n do not. The scanf functions stop at the first character they cannot convert, which is left in the input buffer. The %[^\n] tell it to stop at the first newline. But there is one already there, from the first %d scanf and it needs to be removed, also in subsequent iterations and adding the space does that job. Trying to remove it afterward is clumsy and not guranteed to work.
You must check the return value from scanf every time it is used. It is the number of items successfully scanned. Here, it should be 1 in both uses. So if you have two items in one statement, its return value must be 2.
In the line:
scanf("%[^\n]", &materia[i][50]);
You are storing the inputed string in the address of materia[i][50], effectively storing it outside the bounds of the array.
Something interesting happens here, 2D array storage is contiguous as if it was a one dimensional vector, what happens is you are storing the first string in the beginning of the second line of the array, the second on the third and so on, leaving the first empty. That's the rational for the output the program produces.
Correct you code with:
#include<stdlib.h>
//...
if(scanf(" %49[^\n]", materia[i] != 1) {
puts("Read error");
return EXIT_FAILURE;
}
49 character + the nul terminator to avoid overflow, a space in the beginning of the specifier avoids the consuption of blank characters left in the stdin buffer. Always verify scanf return to avoid reading errors.
Some other issues:
fflush(stdin) should be removed as fflush is meant to be called on an output stream.
Variable lenght arrays can cause stack overflow if enough memory is consumed, in this case it's not likely, but it's something to keep in mind.
Use fgets instead of scanf. The newline character is consumed as a character by your subsequent scanf. That's why you are facing this problem.

warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char'

First of all, this code(PenaltyShootout.c) is used to count the number of 1's in a given string which are preceded by 2.
"0" - No goal,
"1" - Goal,
"2" - Foul.
Problem: PenatltyShootout.exe stopped working.
#include <stdio.h>
#include <string.h>
int main()
{
int T,i;
char str[100][500];
int n=0;
No. of test cases are the no. of different strings to input to check the working of code.
do
{
printf("Enter the number of Test cases(must be between 1 and 100):\n");
scanf("%d",&T);
}while(T>100);
I tried replacing str[i][500] with (char *) str[i][500] and the warning vanished, yet PenaltyShootout.exe stopped working.
for(i=0; i<T; i++)
{
printf("Enter the test case %d\n",i);
scanf("%s",str[i][500]);
}
for(i=0; i<T; i++)
{
for(int j=0; j<strlen(str[i])-1; j++)
{
if((str[i][j]=='2')&&(str[i][j+1]=='1')==1)
{
n++;
}
}
This should print the number of goals made after making a foul.
printf("%d\n",n);
}
return 0;
}
Your call to scanf("%s", str[i][500]); is reading a string ("%s") into a character (str[i][500]).
If you are trying to read a single letter from the prompt, you need to switch it up like this:
scanf("%c", &str[i][500]);
That "%c" lets scanf() know you want a single letter, and that & tells it to use the address of a character in memory (str[i][500], the 501th position in str[i] (when you only have 500 allocated)) for where to put it.
If you are trying to read a string (i.e. a word or sentence) you need to switch it up more like this:
scanf("%s", str[i]);
Here, you are now putting the scanned string into the ith string buffer in str (which you have already allocated 500 chars for).

Alphabetizing a list in C, extra input [duplicate]

This question already has answers here:
scanf issue when reading double
(2 answers)
Closed 5 years ago.
sorry for the remedial question. Been troubleshooting to try and find the error and I have come up empty.
I need to write a program that alphabetizes a list of inputs. The first input is the integer value of the number of inputs. Each input ends with a new line character.
int main()
{
int word_total;
char word_in[100][30], t[30];
int i, j;
printf("\nPlease the number of words you wish to sort: \n");
scanf("%d", &word_total);
printf("\nPlease enter a single word at a time. After each word, press return.\n");
for (i = 0; i < (word_total); i++)
{
scanf("%s\n", word_in[i]);
}
for (i = 1; i < (word_total); i++)
{
for (j = 1; j < (word_total); j++)
{
if (strcmp(word_in[j - 1], word_in[j]) > 0)
{
strcpy(t, word_in[j - 1]);
strcpy(word_in[j - 1], word_in[j]);
strcpy(word_in[j], t);
}
}
}
printf("\nSorted list:\n");
for (i = 0; i < (word_total); i++)
{
printf("%s\n", word_in[i]);
}
printf("\n");
}
The problem: the input of words takes word_total + 1. For instance, if word_total = 5, I have to input 6 words. The last word that is input is ignored and not included in the "Sorted list". I can fix the problem by:
for (i = 0; i < (word_total - 1); i++)
{
scanf("%s\n", word_in[i]);
}
but then the "Sorted list" is short one word. I've tried changing "<" to "<=", etc, but haven't found a fix.
Thank you for your help!
The problem seems to be
scanf("%s\n", word_in[i]);
which, due to the "\n", will attempt to read more whitespace following the string (until it finds another non-whitespace; note that any whitespace character actually means any number of whitespace characters; the \n does not match just a single newline as you apparently expect). You should remove the "\n" from the scanf format and eat the newline with a getchar() or similar.
PS: not testing the return value from scanf() is asking for trouble.

array goes above limit when taking user input

I am taking a couple of numbers as input from the user, storing them into a file and then reading from that file, sorting the numbers and displaying them to the user. The program works except for 1 issue. When taking input from the user it asks for an extra elememnt than the specifies limit. This extra element doesn't get stored anywhere. I have tried reducing the limit value by one but that results in loss of 1 element(i.e. 1 element becomes 0). I understand that this may be a very newbie issue but I coudn't find any direct answer to this issue. I wrote the program in Visual Studio 2010 as a C program. here's the code:
#include <stdio.h>
int arr[50];
int n;
int writefile()
{
FILE *ptr;
ptr = fopen("Sort.txt","w");
if(ptr==NULL)
{
printf("No such file exists\n");
fclose(ptr);
return 0;
}
else
{
int i;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for(i=0; i<n; i++) //The issue is here
{
scanf("%d\n",&arr[i]); //say the user enter n=3, then after adding 1,2,3 it will ask for another 4th element but only 1,2,3 will get stored.
}
fwrite(arr, sizeof(int), n, ptr);
fclose(ptr);
printf("done\n");
}
}
void sortarr(int arr1[]);
int readfile()
{
FILE *ptr;
ptr = fopen("Sort.txt","r");
if(ptr==NULL)
{
printf("No such file exists\n");
fclose(ptr);
return 0;
}
else
{
int i;
int arrb[50];
fread(arrb, sizeof(int), n, ptr);
printf("Before sorting data\n");
for(i=0; i<n; i++)
{
printf("%d",arrb[i]);
}
printf("\n");
sortarr(arrb);
printf("After Sorting data\n");
for(i=0; i<n; i++)
{
printf("%d",arrb[i]);
}
printf("\n");
}
}
void sortarr(int arr1[])
{
int i,j,temp;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr1[i] > arr1[j]) {
temp = arr1[i];
arr1[i] = arr1[j];
arr1[j] = temp;
}
}
}
}
int main()
{
writefile();
readfile();
return 0;
}
scanf("%d\n",&arr[i]);
Should be:
scanf("%d",&arr[i]);
If you ask it to ignore white space after the number, it will have to keep reading until it reads some non-whitespace in order for it to ensure it has ignored all the whitespace. You definitely don't want scanf to try to ignore whitespace after it has read the number, you want it to terminate.
The %d format specifier already ignores whitespace before the number.
Let's just narrow this down to the following code:
scanf("%d", &n);
for (i = 0; i < n; i++)
{
scanf("%d\n", &arr[i]);
}
Notice the difference in the scanf calls? The first call doesn't have a \n in its format string. The second call does.
Remove the \n from the scanf format string (in the second call). Things should work more like you're expecting then.
An online manual page for scanf says:
The format string consists of a sequence of directives which describe how to process the sequence of input characters... A directive is one of the following: A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
So the looped over scanf (with the extra \n in it) was effectively reading the number, the newline, the next number, then realizing it's read all of the white space it could. scanf then returned with the first number assigned to your array entry and the next number ready for the next call to reading from standard input. This left things effectively offset appearing like you saw and requiring the extra number before ending (in order that it could detect that the white space had ended).

Resources