Why is a strange character appearing on my screen? [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 months ago.
Improve this question
I am new to C, I have written a very simple program to get the first name and surname, here is my code...
#include <stdio.h>
#include <conio.h>
int main(){
int num,bankpin;
char fn[20],sn[20];
printf("Welcome to authorization. We ill now begin the process");
printf("\nFirst, please enter your first name: ");
scanf(" %s",fn);
printf("\nEnter your surname: ");
scanf(" %s",sn);
printf("\nWelcome to the system %c %c",&fn,&sn);
return 0;
}
Welcome to authorization. We ill now begin the process
First, please enter your first name: A
Enter your surname: A
Welcome to the system α
Why is this strange "a" appearing on my screen instead of "A A"?
In fact it appears on my screen even if I try a different combination of letters
I have even tried recompiling the code

I'm guessing this is because you are trying to print &fn, which is a pointer, as char. You're basically telling the program to interpret the address o as a symbol code.
Try changing the
printf("\nWelcome to the system %c %c",&fn,&sn) to
printf("\nWelcome to the system %s %s",fn,sn)

Short answer
You are sending the array pointer's address as an argument, and telling printf to interpret it as a single char, resulting in undefined behavior. The fix is to replace the line
printf("\nWelcome to the system %c %c",&fn,&sn);
with
printf("\nWelcome to the system %s %s",fn,sn);
Long answer
The weird character is due to your code reading an unintended value, and trying to interpret it. If you run your code a few times, you will find that you don't always get this symbol, but many other ones, including nothing at all (seemingly). What is going here ?
The short answer is that you are misinforming the printf function by giving her a false symbol and a false value. Let's look at a similar example :
char myString[20] = "Hello!";
printf("%c", &myString);
In this snippet we create an array of characters, which actually means creating a pointer of char* type, and allocating its size (here to 20). Pointers are often confusing when starting with C, but they are in principle pretty simple : they are simply variables that, instead of containing a value, contain an address. Since arrays in C store their value sequentially, that is one after the other, it makes quite a lot of sense to have them be pointers : if you know where the array starts, and that its members are spaced evenly, it makes it quite easy to go over the array.
So since your array is a pointer, reading it directly will print something along the lines of "0x7ffc5a6dbb70". Putting '&' before it gives a very similar result : this operator consists in asking for the address of a variable, which is then in your code transmitted to the printf as an argument.
This doesn't make any sense there : a char is, in C, behind the scene, actually an integer variable with very small capacity, from 0 to 255 to be precise. For example the two lines in the following snippet produce the same result :
printf("%c", 'a');
printf("%c", 97);
Now you see what is happening in the original printf : the function is expecting to receive a very small integer to convert to one character, and instead receives an address, which is the reason why the output is so weird. Since addresses change basically at every run of the code, that is also the reason why the output changes very often.
You thus need to adapt the information in the printf function. First, inform that you wish to print a char array with the symbol "%s". This will make the function expect to receive a pointer to the first element of a char array, which it will then iterate over. Thus, as argument, you need to send this pointer, that you directly have in the form of the myString variable.
Thus running
char myString[20] = "Hello!";
printf("%s", myString);
prints 'Hello!', as expected :)

The funcion scanf is a little tricky, please delete the leading space, inside quotes only include what are you expecting to receive, ever.
scanf("%s",fn);
The printf function needs %s, same as scanf, to deal with string, later you don't need the & operator in this case.
printf("\nWelcome to the system %s %s",fn,sn);

Related

Why can i not use %s instead of %c?

The whole function the question is about is about giving a two dimensional array initialized with {0} as output and making a user able to move a 1 over the field with
char wasd;
scanf("%c", &wasd);
(the function to move by changing the value of the variable wasd is not important i think)
now my question is why using
scanf("%s", &wasd);
does only work partly(sometimes the 1 keeps being at a field and appears a 2nd time at the new place though it actually should be deleted)
and
scanf("%.1s", &wasd);
leads to the field being printed out without stop until closing the execution program. I came up with using %.1s after researching the difference between %c and %s here Why does C's printf format string have both %c and %s?? If one can figure out the answer by reading through that, i am not clever or far enough with c learning to get it.
I also found this fscanf() in C - difference between %s and %c but i do not know anything about EOF which one answer says is the cause of the problem so i would prefer getting an answer without it.
Thank you for an answer
Simple as that, %s is the conversion for a (non-empty) string. A string in C always ends with a 0 byte, so any non-empty string needs at least two bytes. If you pass a pointer to a single char variable, scanf() will just overwrite whatever is in memory after that variable -- you cause undefined behavior and anything can happen.
Side note, scanf("%s", ..), even if you give it an array of char, will always overflow the buffer if something longer is entered, therefore causing undefined behavior. You have to include a field width like
char str[10];
scanf("%9s", str);
Best is not to use scanf() at all. For your single character input, you can just use getchar() (be aware it returns an int). You might also want to read my beginners' guide away from scanf.
A char variable can hold only one byte of memory to hold a single character. But a string (array of characters) is different from a char variable as it is always ended with a null character \0 or numeric 0. So in scanf you specifically mentioned whether you are reading a character or a string so that scanf can add a null character at the end of a string. So you are not suppose to use a %s to read a value for a char variable

Unusual character when writing to file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I've created a struct with 2 char[] and one int. I created an array of this struct and scanfed several inputs to store data into the array. Then I used fprintf to write this data to the file. But when I open the file I get û before every new record. Idk why is it happening.
Here's the relevant code:
FILE *outputFile=fopen("1021.txt","ab");
int tickets=0,i=1;
struct air s[30];
printf("\nEnter Number of tickets:");
scanf("%d",&tickets);
for (i=1;i<=tickets;i++)
{
printf("\nEnter the name\t");
scanf("%s",&s[i].name);
printf("\nEnter the phone number\t");
scanf("%s",&s[i].phoneNo);
printf("\n Enter the address\t");
scanf("%s",&s[i].address);
printf("Your ticket is confirmed\t");
getch();
}
for (i=0;i<=tickets;i++)
{
printf("%s", s[i].name);
printf("%s", s[i].phoneNo);
printf("%s", s[i].address);
fprintf(outputFile,"%s",s[i].name);
fprintf(outputFile,"%s",s[i].phoneNo);
fprintf(outputFile,"%s",s[i].address);
}
Here's what I get in the file:
ûdalla03332228458dallaÈfsÇûÿÿÿÿàrancho03312041265dallabancho
Where are those unusual characters coming from?
Your input loop is
for (i=1;i<=tickets;i++)
but the output loop is
for (i=0;i<=tickets;i++)
So you are writing data to file from element [0] that you have no data entered for. That is why it is junk.
In C, arrays are indexed from [0], and neither of those loops is right. Please change both of them to
for (i = 0; i < tickets; i++)
There are other problems in the code too, but this addresses the immediate "uninitialised data" problem.
Edit: some other problems.
You opened the file in "binary" mode, but you are using it as a text file. I believe the distinction is only necessary in Windows.
FILE *outputFile=fopen("1021.txt", "at"); // change to "t"
The string address passed to scanf should not contain an & address-of (unlike an int). Just pass the array - it decays to the required pointer.
scanf("%s", s[i].name); // removed `&`
As you have not written any newline to file to demark your string data, when you read the data back in, you will not know where each ends and the next begins. So for example, add the newline like this
fprintf(outputFile, "%s\n", s[i].name); // added \n
You say one member is an int presumably the phone number, but you are inputting as a string. Yet it is a bad idea to store phone numbers as integers, because a) thay might contain a character such as '+' or b) may start with a leading 0 and that will be lost when you store as int. So change the struct member phoneNo to be a char array of adequate length.
The scanf format specifier %s will stop at the first whitespace it meets, so the input statements will be better as this, which will only stop when it finds a newline or hits the length limit:
int res = scanf("%29[^\n]", s[i].name);
where the array length defined was [30] (you did not show the struct). Alternatively you could research the use of fgets().
Finally, you should check the return value of the functions you are calling to see if they were successful. fopen will tell you if the file opened correctly. scanf will tell you the number of entries it scanned, and fgets tells you if it was successful too.

Using "gets" for String input in C

I have been trying to get a string input from a user using fgets
but fgets does not wait for input so upon investagation I learned of the gets function which seems to be working fine. My questions are: 1. Why does gets work when I input more than 10 characters if I declared an array of only ten elements. Here is my code
#include<stdio.h>
int main(void){
char name[10];
printf("Please enter your name: ");
gets(name);
printf("\n");
printf("%s", name);
return 0;
}
my input when testing: morethantenletters
will output: 'morethantenletters'
Surely, this should have caused some errors, no? Since name is only ten elements long.
2. My next question is that my code also works when I use gets(&name) instead of gets(name)-- I do not understand why. The &name is sending the address of name.while name is just sending the value of it, no?
That is exactly why you should always use fgets to replace gets. The array name has only 10 elements, but you are trying to store in it more than it's capable of. fgets prevents the program from buffer overflow, but gets doesn't.
It's undefined behavior when you are using gets in this way, don't use it.
Since name is only ten elements long.
Anything accepted more than 10 will be buffer overrun and may cause run time issues. So make sure your size is right. hint: Use getline or fgets instead.
while name is just sending the value of it, no?
For char arrays, name is also address to its starting position.

I am trying to do a program that picks a vowel from the user input [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char *v= "a";
char *o='e';
char * w='i';
char *e='o';
char *l='u';
char *u[1];
printf ("please enter your character\n");
scanf ("%c",& u);
if (u == v){
puts("the character is it a vowel\n");
}
if (u == o) {
puts("the character is it a vowel\n");
}
else
puts("the character is a constant\n");
system("PAUSE");
return 0;
}
i need help in getting the right answer in finding a vowel from the user input.
First of all, shame on you for ignoring all of the compiler warnings you certainly received. They are there to help prevent you from doing "stupid things."
And why all this nonsense? This is the first of the "stupid things" the compiler is trying to tell you about.
char *v= "a";
char *o='e'; // invalid - Initializing a pointer to a constant 'e' (101).
char * w='i'; // invalid
char *e='o'; // invalid
char *l='u'; // invalid
Are you familiar with how pointers work? If not, I suggest you do some reading and understand them.
The first line makes sense - you're making a string and pointing char* v to that string.
But there's really no point in using pointer for those characters - or even variables at all. Just compare them directly:
char my_character;
if (my_character == 'a') {
// do something
}
And as for reading the character, again, you're using pointers when it doesn't make sense:
char *u[1]; // why?
Instead, just define a single char variable. Now, go look at the documentation for scanf. Giving it a format string of "%c" means, "I want to read just one character". Then, you need to tell where scanf to put it. You do this by passing it the "address of" the variable you want to store it in. You do this with (unsurprisingly!) the address of operator &.
char input_character;
scanf("%c", &input_character);
Armed with this information, you should be able to complete your work. Next, I suggest you look into the switch statement.
Finally, you must use consistent formatting (indentation, spacing) and use meaningful variable names, if you have any desire of ever being taken seriously as a programmer. Spelling out "vowel" for your pointless variables may be "cute" but it's total nonsense.
Most importantly, you should never write a single line of code, unless you understand exactly what it does. If you do this, then do not go asking anyone for help (especially not StackOverflow). If you can't explain what your code is doing (or at least what you think it's supposed to do), then you don't deserve for your program to work.

Asking for a name and returning the length of the name in C

I've been struggling with this code for quite some time now.
This is my first time posting here. I am new to C, and I feel that I almost got it.
I have to ask for your name, middle initial, and last name. Then I greet you and tell you the length of your name. Sounds simple enough. I have the following code, I have to use the header file as it is here and that makes things worse. Any help would be greatly appreciated, I feel that I already applied all my knowledge to it and still can't get it to work.
This is my header file:
#ifndef NAME_H_
#define NAME_H_
struct name{
char first[20];
char middle;
char last[20];
};
#endif
and this is my .c file:
#include "name.h"
#include <stdio.h>
#define nl printf("\n");
int strlen(char*s);
char first;
char middle;
char last;
main()
{
printf("enter your first name : ");
scanf("%c", &first);
printf("\n enter your middle initial name : ");
scanf("%c", &middle);
printf("\n enter your last name: ");
scanf("%c", &last);
printf("\n\n Hello %c",first, " %c" ,middle, " %c", last);
printf("\n The String returned the following length: ",strlen);
}
I have t use printf and scanf, then store the name components a name "structure" imported from name.h and lastly use int strlen(char *s); to calculate it.
I get this output with the weird indentation and everything:
enter your first name : Joe
enter your middle initial name :
enter your last name:
Hello J
The String returned the following length: [-my user id]$
Thanks!
Several things about this are not quite right.
First, you shouldn't be declaring strlen yourself. It's a standard C library function, which means you should include the appropriate header. In this case,
#include <string.h>
Second, you're storing the input in variables of type char. Those are literally what they say: they store a single character. So unless you're only allowing people to have single-character names, you need a bit more than that. This sort of string input problem is actually rather tricky in C, since you have to do explicit memory management and don't know how much data the user is going to send you in advance. One of the simpler things is to just use a large buffer and truncate, but for a more complex program you'd want to do error handling and possibly dynamically resize the buffer. But for starters:
char first[1024];
char middle[1024];
char last[1024];
will at least get you started. Your struct name has some of this, but you're not currently using it (and the sizes are pretty small).
Next, scanf is a tricky way to get input strings. scanf of a %s pattern will happily read more than 1024 characters and write over the end of the buffer and destroy your program. This is why C programmers usually read input data using fgets instead, since then you can more easily say how big of a buffer you're willing to read:
fgets(first, sizeof(first), stdin);
Be aware that if the user enters more than 1023 characters, it will read the first 1023 characters and then leave the rest there, where you'll end up reading it as part of the middle name. String handling in C is complex! C is not good at this sort of thing; that's why people tend to use Perl or similar languages for this sort of interactive string handling where you don't know sizes in advance. In C, you have to pursue a strategy like repeatedly calling fgets until you get a newline at the end of the result and then deciding whether to dynamically resize your data structure or throw an error. Alternately, you can use scanf with %1023s but you need to qualify the format to specify the maximum length. The syntax is a bit weird and tricky; fgets is simpler when you're reading character strings.
As mentioned in the other answer, strlen is a function that you need to call on a char * variable (or char array) to get the length of the string it holds. You probably want to call it on first, middle, and last and add them together.
Finally, in your last printf, you have to pass one format and then all of the arguments for that format. You want something more like:
printf("\n\n Hello %s %s %s", first, middle, last);
(once you fix the type of those variables).
This is a lot of random detail. I hope it helps some. The important brief takeaway is that a string in C is a sequence of char ending in a char with a value of 0, and all C data structures have to be sized in advance (either statically or dynamically with malloc). C furthermore has no bounds checking, so it's completely up to you to ensure that you only read as much data as you created space for.
use
strlen(first)
to get the length of variable first ..similarly for other varibles... To get the cumulative length use
printf("\n Length: ",strlen(first)+strlen(middle)+strlen(last));

Resources